- 希尔排序又叫缩小增量排序,是插入排序的改进,是不稳定排序。
- 先确定一个增量,将整个序列分成几个小组,再在小组中进行插入排序,一轮下来之后,前面的数是相对小的,后面是相对大的。再改变增量,每次减少一半,最后直到增量为1,对整个序列进行插入排序。
- 增量的确定:在一篇博客上看到初始增量设置为(数组长度)/3+1,这样效率高,但我并未找到原因,别的博客,百度百科,维基百科等为(数组长度)/2。反正保证最后增量为1就行。
维基百科代码更简洁
public static void shellSort(int[] arr) {
int length = arr.length;
int temp;
for (int step = length / 2; step >= 1; step /= 2) {
for (int i = step; i < length; i++) {
temp = arr[i];
int j = i - step;
while (j >= 0 && arr[j] > temp) {
arr[j + step] = arr[j];
j -= step;
}
arr[j + step] = temp;
}
}
}
我的代码
public class ShellSort {
public static void main(String[] args) {
int[] arr = {12,43,23,56,13,24,58,90,62,67,34};
Sort(arr);
for(int i=0;i<arr.length;i++) {
System.out.println(arr[i]);
}
}
static void Sort(int[] a) {
for(int gap=a.length/3+1;gap>0;gap/=2) {//让gap从a.length/3+1逐步到一,控制分组增量
for(int i=0;i<gap;i++) {//下面即为插入排序
for(int j=i+gap;j<a.length;j+=gap) {
int k=j-gap;
int temp=a[j];
while(k>=0&&a[k]>temp) {
a[k+gap]=a[k];
k-=gap;//这里结束后,k=k-gap,后面将目标值a[j](即gap)移到目标位置应该加上
}
a[k+gap]=temp;//这里k=k-gap。要使位置正确,要加上gap
}
}
}
}
}