希尔排序是建立在插入排序之上的
他是以每次以不同的步长将序列分组后对不同的组排序
如图:
这里的步长是4,排序完0,4,8后,再来排序1,5,9。2,6。3,7
如图:
排序完后在进行依次这样的排序,这次如果是以2为步长的话,那么第八位的数字7很容易就排到了第六位数字8的前面。所以将不同的步长结合起来使用更有效。
步长的计算公式h=3*h+1 h要小于序列的长度
import java.util.Arrays;
/**
* 希尔排序
* @author zx
*
*/
public class ShellSort {
public static void shellSort(int[] array){
//计算步长
int step = 1;
while(step < array.length/3){
step = step * 3 +1;
}
while(step > 0){
for(int i=step;i<array.length;i++){
int temp = array[i];
int index = i;
while(index - step >= 0 && array[index - step] >= temp){
array[index] = array[index -step];
index = index - step;
}
array[index] = temp;
}
step = (step - 1)/3;
}
}
public static void main(String[] args) {
int[] array = new int[10];
for(int i=0;i<10;i++){
array[i] = (int)(Math.random()*99);
}
System.out.println(Arrays.toString(array));
shellSort(array);
System.out.println(Arrays.toString(array));
}
}