本人亲测可用,纯手打
package Sort;
//希尔排序
public class XiErSort {
public static void printArray(int[] a) {
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}
System.out.println("");
}
public static void xiErSort(int[] a){
int temp = 0;
int h,j;
for(h = a.length/2;h>0;h = h /2){
for(int k = h; k<a.length ;k = k+1){
temp = a[k];
j = k;
while(j>=h){//直接插入排序,按照h来进行插入
if(a[j-h]>temp){
a[j]=a[j-h];
}else{
break;
}
j=j-h;
}
a[j] = temp;
}
System.out.println(h);
printArray(a);
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] a = { 49,38,65,97,76,13,27,49,55,04,38, 65, 97, 76, 13, 27, 49, 2, 78, 75, 56, 48, 89, 10, 3,
852 };
printArray(a);
xiErSort(a);
//printArray(a);
}
}
结果:
49 38 65 97 76 13 27 49 55 4 38 65 97 76 13 27 49 2 78 75 56 48 89 10 3 852
步长为:13
49 13 27 49 2 13 27 49 48 4 10 3 97 76 38 65 97 76 78 75 56 55 89 38 65 852
步长为:6
27 13 27 4 2 3 49 49 38 49 10 13 65 75 48 55 89 38 78 76 56 65 97 76 97 852
步长为:3
4 2 3 27 10 13 49 13 27 49 49 38 55 75 38 65 76 48 65 89 56 78 97 76 97 852
步长为:1
2 3 4 10 13 13 27 27 38 38 48 49 49 49 55 56 65 65 75 76 76 78 89 97 97 852