JAVA常用排序算法之希爾排序
希爾排序是直接插入排序的一種改進,這是一種不穩定的算法。
具體的實現方式如下:設定增量,讓兩個數字進行比較,然後調換位置。舉個例子,32,15,78,24,22,78,11先設置增量爲3,那麼就是將32和24進行比較,32更大,調換位置。然後依次向後比較,將整個數組變成基本有序(就是大的數字基本在後面,小的數字基本在前面)。注意,最後一個增量一定要設置爲1。
算法的平均時間複雜度爲O(n×log(n))
實現的代碼如下:
public class HillSort {
public static void main(String[] args) {
//需要排序的數組
int[] arr = {55, 234, 19, 236, 11, 563, 111};
//設置增量的數組
int[] increase = {3, 1};
hillSort(increase, arr);
print(arr);
}
//打印的方法
private static void print(int[] arr) {
for (int i : arr
) {
System.out.println(i);
}
}
//希爾排序的方法
private static void hillSort(int[] increase, int[] arr) {
int temp;
for (int i = 0; i < increase.length; i++) {
for (int j = 0; j < arr.length; j++) {
//根據增量進行比較
if (j + increase[i] < arr.length) {
if (copare(arr[j], arr[j + increase[i]])) {
temp = arr[j];
arr[j] = arr[j + increase[i]];
arr[j + increase[i]] = temp;
}
}
}
}
}
//兩個數字比較大小
private static boolean copare(int a, int b) {
return a > b ? true : false;
}
}