希尔排序(最小增量排序)
基本思想:希尔排序是把记录按下标的一定增量分组,对每组使用直接插入排序算法排序;随着增量逐渐减少,每组包含的关键词越来越多,当增量减至1时,整个文件恰被分成一组,算法便终止。
package sortalgorithm;
public class PublicShellSort {
static void shellSort() {
int[] sortList = { 1, 3, 2, 4, 10, 7, 8, 9, 5, 6 };
int n = 1,len = sortList.length;
for (int step = len / 2; step > 0; step /= 2) {
for (int i = 0; i < step; i++) {
for (int j = i + step; j < len; j += step)
if (sortList[j] < sortList[j - step]) {
//如果后面的数大于前面的数,则两两进行交换
int temp = sortList[j];
int k = j - step;
while (k >= 0 && sortList[k] > temp) {
sortList[k + step] = sortList[k];
k -= step;
}//该循环是位移式
sortList[k + step] = temp;
}
}
System.out.println("第" + n + "次:");
for (int m = 0; m < sortList.length; m++) {
System.out.print(sortList[m] + " ");
}
System.out.println();
n++;
}
System.out.println("最终:");
for (int k = 0; k < sortList.length; k++) {
System.out.print(sortList[k] + " ");
}
}
public static void main(String[] args) {
shellSort();
}
}
运行结果: