希尔排序(Shell Sort)是改进型的插入排序的一种,也称缩小增量排序。它比普通插入排序的效率要更高。希尔排序是非稳定排序算法。
该方法的基本思想是:先将整个待排元素序列分割成若干个子序列(由相隔某个“增量”的元素组成的)分别进行直接插入排序,然后依次缩减增量再进行排序,待整个序列中的元素基本有序(增量足够小)时,再对全体元素进行一次直接插入排序。因为直接插入排序在元素基本有序的情况下(接近最好情况),效率是很高的,因此希尔排序在时间效率上比前两种方法有较大提高。
伪代码
input: an array a of length n with array elements numbered 0 to n − 1
inc ← round(n/2)
while inc > 0 do:
for i = inc .. n − 1 do:
temp ← a[i]
j ← i
while j ≥ inc and a[j − inc] > temp do:
a[j] ← a[j − inc]
j ← j − inc
a[j] ← temp
inc ← round(inc / 2.2)
Java代码
package 算法;
//希尔排序
public class Demo5 {
public static void shellSort(int arr[]){
int len =arr.length;//数组长度
int m,n,k;
int temp;
for(m=len/2;m>0;m=m/2){//间隔长度m依次从二分之一数组长到一
for(n=m;n<len;n++){//每次从间隔长的第一位开始依次往前以间隔m长度向前比较
temp=arr[n];//每次记下比较位置,类似于插入比较法,
for(k=n-m;k>=0;k=k-m){
if(temp<arr[k]){
arr[k+m]=arr[k];}
else{break;}
}
arr[k+m]=temp;
}
}
}
public static void main(String[] args){
int a[]={7,4,8,0,3,5,2,1,6,10,27,12,23};
shellSort(a);
for(int i=0;i<a.length;i++){
System.out.println(a[i]);
}
}
}
输出结果
1
2
3
4
5
6
7
8
10
12
23
27