- 基本思想:
算法先將要排序的一組數(shù)按某個增量d(n/2,n為要排序數(shù)的個數(shù))分成若干組,每組中記錄的下標相差d.對每組中全部元素進行直 接插入排序,然后再用一個較小的增量(d/2)對它進行分組,在每組中再進行直接插入排序。當增量減到1時,進行直接插入排序后,排序完成。
- 代碼實現(xiàn):
/**
* 打印數(shù)組內(nèi)容
*
* @param a
*/
public static void saymsg(int[] src) {
for (int i = 0; i < src.length; i++) {
System.out.print(src[i]);
System.out.print(" ");
}
System.out.println();
}
/**
- 希爾排序
- @param src
*/
public static void shellSort(int[] src) {
double d1 = src.length;
int temp = 0;
int index = 1;
while (true) {
d1 = Math.ceil(d1 / 2);
int d = (int) d1;
for (int x = 0; x < d; x++) {
for (int i = x + d; i < src.length; i += d) {
int j = i - d;
temp = src[i];
for (; j >= 0 && temp < src[j]; j -= d) {
src[j + d] = src[j];
}
src[j + d] = temp;
}
System.out.println("第" + (index++) + "次排序:");
saymsg(src);
}
if (d == 1)
break;
}
saymsg(src);
}
public static void main(String[] args) {
int[] src = { 49, 38, 65, 97, 76, 13, 27, 49, 78, 34, 12, 64, 5, 4, 62, 99, 98, 54, 56, 17, 18, 23, 34, 15, 35,
25, 53, 51 };
System.out.println("原始數(shù)組排序:");
saymsg(src);
shellSort(src);
}
![](//atts.w3cschool.cn/attachments/image/20170727/1501145470681237.gif)
*圖片來自維基百科*
更多建議: