原理:对于n个待排序的数列,取一个小于n的整数gap(gap被称为步长)将待排序元素分成若干个组子序列,所有距离为gap的倍数的记录放在同一个组中;然后,对各组内的元素进行直接插入排序。 这一趟排序完成之后,每一个组的元素都是有序的。然后减小gap的值,并重复执行上述的分组和排序。重复这样的操作,当gap=1时,整个数列就是有序的。
代码:
public class ShellSort { public static void main(String[] args) { int i; int a[] = {80, 30, 60, 40, 20, 10, 50, 70}; System.out.printf("before sort:"); for (i = 0; i < a.length; i++) System.out.printf("%d ", a[i]); System.out.printf("\n"); shellSort1(a, a.length); System.out.printf("after sort:"); for (i = 0; i < a.length; i++) System.out.printf("%d ", a[i]); System.out.printf("\n"); } public static void shellSort1(int[] a, int n) { //gap为步长,每次减为原来的一半。 for (int gap = n / 2; gap > 0; gap /= 2) { //共有gap个组,对每组进行直接插入排序 for (int i = 0; i < gap; i++) { for (int j = i + gap; j < n; j += gap) { //如果a[j]<a[j-gap],则寻找a[j]位置,并将后面数据的位置都后移 if (a[j] < a[j - gap]) { int tem = a[j]; int k = j - gap; while (k >= 0 && a[k] > tem) { a[k + gap] = a[k]; k -= gap; } a[k + gap] = tem; } } } } } }
结果:
参考博客:https://www.cnblogs.com/chengxiao/p/6104371.html
https://www.cnblogs.com/skywang12345/p/3597597.html#a43