Shell排序(Shell’ Sort),是对简单的插入排序的改进,改进的思路是,由于插入排序在数据基本有序时,其时间复杂度较小,特别的当数据有序时其时间复杂度为O(n),故如果我们可以将一个待排序的数据在排序前能够做到基本有序,那么利用插入排序是个非常好的选择,这也就是Shell排序的思想。
Shell排序的基本做法是,首先以一定的大间隔对数据进行排序,然后间隔不断缩小,继续进行排序,那么待排序的数据,就会逐渐变得基本有序,最后在用简单的插入排序,即间隔为1,因此希尔排序也被称为缩小增量排序(Dimininshing Increment Sort)
如对 5 6 8 7 1 3 15进行排序
间隔为3时
5 6 8 7 1 3 15 ===> 5 1 8 7 6 3 15 ===>5 1 3 7 6 8 15
间隔为2时
5 1 3 7 6 8 15 ===> 3 1 5 7 6 8 15 ===> 3 1 5 7 6 8 15
间隔为1时
3 1 5 7 6 8 15 ===>1 3 5 7 6 8 15 ===>1 3 5 7 6 8 15===>1 3 5 7 6 8 15===>1 3 5 6 7 8 15
===>1 3 5 6 7 8 15===>1 3 5 6 7 8 15
import java.util.Scanner;
public class ShellSortTest {
/**
* funcation:以传入的增量为间隔,进行一次插入排序
* @param array 待排序数组,其中数组的第一个元素array[0],不存实际的数据,用做辅助空间
* @param increment 增量间隔
*/
private static void shellInsert(int[] array, int increment) {
for (int i = increment + 1; i < array.length; i++) {
if (array[i] < array[i - increment]) {
array[0] = array[i]; //array中array[0]作为临时存储单元
int j;
//以增量为间隔,向前寻找比当前数据大的
for (j = i - increment; j > 0 && array[0] < array[j]; j -= increment) {
array[j + increment] = array[j];//若找到的数据比当前待比较的数据大则以增量为间隔,向后移动
}
array[j + increment] = array[0];//将当前数据,插入到找到的位置中
}
}
}
/**
* function:Shell插入排序,也叫缩小增量排序
* @param array 待排序数组
* @param icAry 增量数组,其中最后一个元素必须为1,也即最后一个增量必须为1
*/
public static void shellSort(int[] array,int[] icAry){
for (int i = 0; i < icAry.length; i++) {
shellInsert(array,icAry[i]);
}
}
/**
* function:输入数组ary[1...end]中的数据
* @param ary 待输出数组
*/
private static void show(int[] ary){
for (int i = 1; i < ary.length; i++) {
System.out.print(ary[i]+" ");
}
}
private static int[] getData(){
Scanner sc = new Scanner(System.in);
System.out.println("请输入待排序数据总个数:");
int totalNums = sc.nextInt();
int[] inputData = new int[totalNums+1];
System.out.print("请输入待排序数据,以空格作为分隔符:");
for (int i = 1; i < inputData.length; i++) {
inputData[i]=sc.nextInt();
}
return inputData;
}
public static void main(String [] args){
int[] inputData=ShellSortTest.getData();//获取待排序数据
int[] increment={5,4,2,1};//自定义的增量数组
ShellSortTest.shellSort(inputData, increment);//Shell插入排序
ShellSortTest.show(inputData);//显示排序后的结果
}
}