您的位置:首页 > 其它

算法(第四版)——04希尔排序

2016-11-11 17:16 141 查看
public class ShellSort {
public static void main(String[] args) {
int[] a = {45,67,43,28,90,15,77,88};
System.out.print("排序前的顺序:");
for (int i : a) {
System.out.print(i + " ");
}
System.out.println();
System.out.println("排序过程:");
shellSort(a);
System.out.print("排序后的顺序:");
for (int i : a) {
System.out.print(i + " ");
}
}

private static void shellSort(int[] a) {
// TODO Auto-generated method stub
int N = a.length;
int h = 1;
while(h < N/3) {
h = h*3 + 1;
}
while(h>0) {
for (int i = h; i < N; i++) {
for (int j = i; j>=h && (a[j]<a[j-h]); j = j-h) {
int temp = a[j];
a[j] = a[j-h];
a[j-h] = temp;
for (int k : a) {
System.out.print(k + " ");
}
System.out.println();
}
}
h = h/3;
}
}
}

运行结果:

排序前的顺序:45 67 43 28 90 15 77 88 

排序过程:

45 15 43 28 90 67 77 88 

15 45 43 28 90 67 77 88 

15 43 45 28 90 67 77 88 

15 43 28 45 90 67 77 88 

15 28 43 45 90 67 77 88 

15 28 43 45 67 90 77 88 

15 28 43 45 67 77 90 88 

15 28 43 45 67 77 88 90 

排序后的顺序:15 28 43 45 67 77 88 90 

理解不充分,日后有时间再来记录
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: