我想希爾排序 應該算 插入排序的一個優化。把一個數組按規則分割成若干個子序列,
然後沒子序列進行直接插入排序。然後縮小增量,對之前有過一次排序的數組,再分割,再進行插入排序,最後增量爲1,數組基本有序了,執行最後一次 直接插入排序。
下邊是我從其他人的博客抄的一段話,希望對大家理解起來有所幫助。
希爾排序的基本思想是:先將整個待排元素序列分割成若干個子序列(由相隔某個“增量”的元素組成的)分別進行直接插入排序,然後依次縮減增量再進行排序,待整個序列中的元素基本有序(增量足夠小)時,再對全體元素進行一次直接插入排序。因爲直接插入排序在元素基本有序的情況下(接近最好情況),效率是很高的,因此希爾排序在時間效率上比前兩種方法有較大提高。
下邊是我做的測試類,一個數組是 49, 38, 65, 97, 26, 13, 27, 49, 55, 4,11。
第一趟按照 增量爲5 進行分割子序列(5組),每組的下標是0 5 10; 1 6 ; 2 7 ; 3 8 ;4 9
然後對每組進行直接插入排序。
第二趟按照 增量爲2,分割成兩組 。
第三趟按照增量爲1 ,也就是隻分割成了1組 ,直接插入排序。
import java.util.Arrays; public class Array { // 把11個數的數組,分成三組 static void group(){ //0 5 10; 1 6 ; 2 7 ; 3 8 ;4 9 int [] ia = {49, 38, 65, 97, 26, 13, 27, 49, 55, 4,11}; // 把數組分成三組 int gap = ia.length/2; int count = 0; while(count<gap){ int i = count; while(i<ia.length){ System.out.println(ia[i]); i = i+gap; } count++; } } // 希爾排序 static void shellSort(){ int [] ia = {49, 38, 65, 97, 26, 13, 27, 49, 55, 4,11}; System.out.println("原始數據:"+ Arrays.toString(ia)); // 把數組分成三組 int gap = ia.length/2; // 0 5 10; 1 6 ; 2 7 ; 3 8 ;4 9 int count = 0; while (gap>=1) { while(count<gap) { int original = count+gap; // 表示從每組的哪個下標開始進行插入排序 ,即從每組第二個下標開始的 5,6,7,8,8,9開始進行插入排序 while(original<ia.length) { int current = original; // current 當前要 進行插入排序的元素的下標 int previous = original-gap; while(previous>=0 && (ia[previous]>ia[current])) { // if() { int temp ; temp = ia[previous]; ia[previous] = ia[current] ; ia[current] = temp; current = current-gap; previous = previous-gap; // } } original = original+gap; } //original<ia.length while end count++; } System.out.println(Arrays.toString(ia)); //打印每趟循環後的元素變化 gap = gap/2; count = 0; } System.out.println("排好序的數據"+Arrays.toString(ia)); } /** * @param args */ public static void main(String[] args) { shellSort(); }