希爾排序是插入排序的進化版,在進行比交換位置時以增量進行交換或移動;經過比較相距必定間隔的元素來工做;各趟比較所用的距離隨着算法的進行而減少,直到只比相鄰元素的最後一趟排序爲止,所以有時也叫縮減增量排序算法
直接上代碼吧(可能並非最好的例子):shell
public void shellSort(){ int[] a = {81,94,11,96,12,35,17,95,28,58,41,75,15}; System.out.println(Arrays.toString(a)); int j; for (int gap = a.length/2; gap > 0 ; gap /= 2) { for (int i = gap; i < a.length; i++) { int tmp = a[i]; for (j = i; j >= gap && tmp < a[j-gap] ; j -= gap) { a[j] = a[j-gap]; } a[j] = tmp; } } System.out.println(Arrays.toString(a)); }
以gap=3爲例,結合代碼:數組
public void shellSort(){ int[] a = {15, 94, 11, 58, 12, 35, 17, 95, 28, 96, 41, 75, 81};//gap=3以前的數組 System.out.println(Arrays.toString(a)); int j; for (int gap = a.length/2; gap > 0 ; gap /= 2) { for (int i = gap; i < a.length; i++) { int tmp = a[i];//tmp for (j = i; j >= gap && tmp < a[j-gap] ; j -= gap) { a[j] = a[j-gap]; //15, 94, 11, 58, 94, 35, 17, 95, 28, 96, 41, 75, 81 //15, 12, 11, 58, 94, 35, 58, 95, 28, 96, 41, 75, 81 //15, 12, 11, 17, 94, 35, 58, 95, 35, 96, 41, 75, 81 //15, 12, 11, 17, 94, 28, 58, 95, 35, 96, 95, 75, 81 //15, 12, 11, 17, 94, 28, 58, 94, 35, 96, 95, 75, 81 //15, 12, 11, 17, 41, 28, 58, 94, 35, 96, 95, 75, 96 } a[j] = tmp; }
//gap=3以後的數組:[15, 12, 11, 17, 41, 28, 58, 94, 35, 81, 95, 75, 96] } System.out.println(Arrays.toString(a)); }
希爾排序與插入排序不一樣的是:希爾排序是增量式的不想普通的插入排序一個一個的往前比較,而是按增量進行大間距的移動或交換spa