package sort;
public class ShellSort {
/*
* 0 1 2 3 4 5 6 7 8 9 // 坐标 0 4 1 5 7 3 10 8 2 55 0 4 1 5 2 3 10 8 7 55 //
* 间隔h=4 一次插入排序坐标为0,4,8 对应值0,7 ,2排序 循环间隔h=4, 对坐标 1,5,9对应值4,3,55排序 0 2 7 3 4
* 55 1 10 5 8
*
* 0 3 1 5 2 4 10 8 7 55 // 一个间隔排序完成 ,基本有序,减小了移动次数 间隔h=1 进行如上操作
*/
public static void shellSort(int a[]) {
// Knuth 间隔序列
int h = 1;
int temp = 0;
int i = 0;
int j = 0;
while (h < a.length / 3) {
h = h * 3 + 1;
// System.out.println("序列间隔:"+h);
}
// 对h增量插入排序
while (h > 0) {
for (i = h; i < a.length; i = i + h) {// 一次间隔要循环a.length-h次 ,改进在此处 i=i+h;网上很多都是i++,ms不对
// System.out.println(i+"---"+h);
temp = a[i]; // 存储临时值
j = i; // j 指针变量,向temp 后前移动
while (j > 0 && a[j - h] >= temp) {
a[j] = a[j - h];
j -= h;
}
a[j] = temp;
// System.out.println(j+"J:"+a[j]);
}
h = (h - 1) / 3;// 减小间隔
}
}
public static void main(String[] args) {
long startTime = System.currentTimeMillis();
int a[] = { 10, 9,3,1 };
int num = 10000;
int b[] = new int[num];
for (int i = 0; i < b.length; i++)
b[i] = num - i;
shellSort(a);
shellSort(b);
System.out.println("对数组a 进行排序结果");
for (int j = 0; j < a.length; j++)
System.out.print(a[j] + "-->");
System.out.println();
System.out.println("对数组b进行排序结果");
int n = 0;
for (int k : b) {
n++;
System.out.print(k + "-->");
if (n % 10 == 0)
System.out.println();
}
long endTime = System.currentTimeMillis();
System.out.println(endTime - startTime + "ms");
}
}