# 希尔排序

/**
* 希尔排序
* @author D N
*
*/
public class ShellSort {
private long[] a;
private int nElems;

public ShellSort(int max){
a = new long[max];
nElems = 0;
}

public void insert(long value){
a[nElems] = value;
nElems++;
}

public void display(){
for(int j=0;j<nElems;j++){
System.out.print(a[j]+"   ");
}
System.out.println("");
}

//希尔排序算法
public void shellSort(){
int inner,outer;
long temp; // 临时变量

int h = 1; //数据项之间的间隔，排序时按此间隔排序
while(h <= nElems/3 ){
h = h*3+1;
}

while(h > 0){ //不断减少h，直至h = 1，此时排序成为了插入排序
for(outer = h;outer < nElems;outer++){
temp = a[outer];
inner = outer;
while(inner > h-1 && a[inner-h] >= temp){
a[inner] = a[inner-h];
inner -= h;
}
a[inner] = temp;
}
h = (h-1)/3;
display();
}

}
}

public class SortTest {
public static void main(String[] args) {
int maxSize = 10;
ShellSort arr = new ShellSort(maxSize);
arr.insert(7);
arr.insert(10);
arr.insert(1);
arr.insert(9);
arr.insert(2);
arr.insert(5);
arr.insert(8);
arr.insert(6);
arr.insert(4);
arr.insert(3);
arr.display();
System.out.println();
arr.shellSort();
System.out.println();
arr.display();
}
}

7   10   1   9   2   5   8   6   4   3

2   3   1   6   4   5   8   9   7   10
1   2   3   4   5   6   7   8   9   10

1   2   3   4   5   6   7   8   9   10   

posted @ 2019-01-28 15:26  51life  阅读(...)  评论(...编辑  收藏