Comb Sort ใน Java จะกำจัดค่าที่น้อยกว่าที่อยู่ท้ายรายการ และการผกผันจะถูกลบออกทีละรายการ เรามาดูตัวอย่างกัน −
ตัวอย่าง
import java.util.Arrays;
public class Demo{
void comb_sort(int nums[]){
int len_gap = nums.length;
float shrink_val = 1.3f;
boolean swap = false;
while (len_gap > 1 || swap) {
if (len_gap > 1) {
len_gap = (int)(len_gap / shrink_val);
}
swap = false;
for (int i = 0; len_gap + i < nums.length; i++){
if (nums[i] > nums[i + len_gap]) {
swap(nums, i, i + len_gap);
swap = true;
}
}
}
}
private static void swap(int nums[], int x, int y) {
Integer temp = nums[x];
nums[x] = nums[y];
nums[y] = temp;
}
public static void main(String args[]){
Demo ob = new Demo();
int nums[] = {6, 78, 90, -12, -45, 0, -1, 45};
System.out.println("The original array contains ");
System.out.println(Arrays.toString(nums));
ob.comb_sort(nums);
System.out.println("The sorted array is ");
System.out.println(Arrays.toString(nums));
}
} ผลลัพธ์
The original array contains [6, 78, 90, -12, -45, 0, -1, 45] The sorted array is [-45, -12, -1, 0, 6, 45, 78, 90]
คลาสชื่อ Demo มีฟังก์ชัน 'comb_sort' ในที่นี้ ความยาวของอาร์เรย์ถูกกำหนดไว้แล้ว และหากความยาวนี้มากกว่า 1 จะมีการกำหนด 'len_gap' ใหม่ นั่นคือความยาวของอาร์เรย์หารด้วย 1.3f
อาร์เรย์นี้มีการทำซ้ำและองค์ประกอบในอาร์เรย์จะถูกเปรียบเทียบ และหากองค์ประกอบนั้นมากกว่าองค์ประกอบบวกกับ 'len_gap' เฉพาะ องค์ประกอบจะถูกสลับ หลังจากนี้ จะมีการจัดเรียงฟองอากาศอย่างง่ายกับองค์ประกอบต่างๆ ในฟังก์ชันหลัก อาร์เรย์จะถูกกำหนดและอินสแตนซ์ของคลาส Demo ถูกกำหนดและฟังก์ชัน 'comb_sort' จะถูกเรียกใช้ในอาร์เรย์