Shell排序
实现步骤:
1.将有 n 个元素的数组分成 n/2 个数字序列,第一个数据和第 n/2+1 个数据为一对, ………..
2.一次循环使每一个序列对排好顺序。
3.然后,再变为 n/4 序列, 再次排序。
4.不断重复上序过程,随着序列减少最后变为一个,也就完成了整个排序。
示例代码如下:
void ShellSort(int []a){
int i,j,h;
int r,temp;
int x = 0;
for (r = a.length/2; r >= 1; r/=2){
for (i = r; i < a.length; i++) {
temp = a[i];
j = i - r;
while (j >= 0 && temp < a[j]){
a[j + r] = a[j];
j -= r;
}
a[j + r] = temp;
}
x ++;
System.out.print("第" + x + "步排序结果:");
for (h = 0; h < a.length; h++){
System.out.print(" " + a[h]);
}
System.out.print("\n");
}
}
public static void main(String[] args) {
int [] a = { 5, 1, 6, 9, 3, 8, 7, 54, 61, 52, 124, 76, 90};
ShellSort(a);
}
实现结果:
第1步排序结果: 5 1 6 9 3 8 7 54 61 52 124 76 90
第2步排序结果: 5 1 6 7 3 8 9 54 61 52 124 76 90
第3步排序结果: 1 3 5 6 7 8 9 52 54 61 76 90 124