### 希尔排序与插入排序
希尔排序是插入排序的优化版 。希尔排序也叫增量缩小排序。希尔排序就要排序的数组进行分组,分多少组(数组的大小除以2)。
每组元素之间相隔它的增量(数组size/2),如:3 4 5 1 ,增量为4/2=2分为两组。3 5 4 1组成一组。
1. 先对要进行排序的数组进行分组
2. 对各组分别进行插入排序
3. 重复1.2步直到只有一组时即增量为1时,进行最后一次插入排序,然后排序成功;
package 排序;
import javax.swing.tree.DefaultTreeCellEditor;
import java.lang.reflect.Array;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.SimpleTimeZone;
public class 希尔排序o插入 {
public static void main(String[]args){
// 待排序数组: 8 9 1 7 2 3 5 4 6 0
// int[] array=new int[]{8,9,1,7,2,3,5,4,6,0};
int [] array=new int[8];
for (int i = 0; i
array[i]=(int)(Math.random()*8000000);
}
Date date1=new Date();
SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String d=simpleDateFormat.format(date1);
System.out.println(d);
xiEr(array);
Date date2=new Date();
SimpleDateFormat simpleDateFormat2=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String d2=simpleDateFormat2.format(date2);
System.out.println(d2);
}
// 静态工具方法
public static void xiEr(int[] array){
//综上每一轮的插入排序写成循环
int temp=0;
for(int zen=array.length/2;zen>0;zen=zen/2){
for(int i=zen;i
for (int j = i-zen; j >=0 ; j=j-zen) {
if(array[j]>array[j+zen]){
temp=array[j];
array[j]=array[j+zen];
array[j+zen]=temp;
}
}
}
// System.out.println(Arrays.toString(array));
}
}
}
- 希尔排序,将要排序的数组分成几组分别进行排序,排序完后数组里的数,小的越靠前,大的越靠后。数组里的数更显有有序,当只有最后一组时,相当于进行一次插入排序,测时不用需要比较和移动多位数即可排序完。