希尔排序,先确定增量,根据增量分组进行插入排序
/*
* shell sort
* @Author: lvlang1993
* */
public class ShellSort {
public static void main (String[] args) {
int[] data = new int[] { 5, 2, 8, 9, 1, 3 ,4, 75, 4, 9, 24, 7};
System.out.println("未排序前");
for (int i = 0; i < data.length; i++){
System.out.print(data[i] + " ");
}
System.out.println();
sort(data);
System.out.println("\n排序后");
for (int i = 0; i < data.length; i++)
System.out.print(data[i] + " ");
}
/*
* 确定增量,然后根据增量分组并用插入排序的方法进行排序
* @Param: data[], the array to be sorted
* @Return
* */
public static void sort(int[] data) {
int j = 0;
int temp = 0;
for (int increment = data.length / 2; increment > 0; increment /= 2) {//确定增量
for (int i = increment; i < data.length; i++) {//分组
temp = data[i];
for (j = i; j >= increment; j -= increment) {//插入排序
if(temp > data[j - increment]){
data[j] = data[j - increment];
}else{
break;
}
}
data[j] = temp;
}
}
}
}