Comb Sort trong Java loại bỏ các giá trị nhỏ ở cuối danh sách và đảo ngược (inversions) bị loại bỏ một per one. Hãy xem ví dụ:
Ví dụ
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("Mảng gốc chứa: ");
System.out.println(Arrays.toString(nums));
ob.comb_sort(nums);
System.out.println("Mảng đã sắp xếp: ");
System.out.println(Arrays.toString(nums));
}
}
Kết quả
Mảng gốc chứa [6, 78, 90, -12, -45, 0, -1, 45] Mảng đã sắp xếp [-45, -12, -1, 0, 6, 45, 78, 90]
Lớp Demo chứa hàm comb_sort. Độ dài mảng định nghĩa, nếu lớn hơn 1, len_gap mới là độ dài chia 1.3f.
Mảng duyệt qua, phần tử so sánh và nếu phần tử lớn hơn phần tử cộng len_gap, hoán đổi. Sau đó, bubble sort đơn giản cũng thực hiện. Trong main, mảng định nghĩa, instance Demo tạo và comb_sort gọi.