希尔排序是插入排序的进化版,在进行比交换位置时以增量进行交换或移动;通过比较相距一定间隔的元素来工作;各趟比较所用的距离随着算法的进行而减小,直到只比相邻元素的最后一趟排序为止,因此有时也叫缩减增量排序
直接上代码吧(可能并不是最好的例子):
public void shellSort(){ int[] a = {81,94,11,96,12,35,17,95,28,58,41,75,15}; System.out.println(Arrays.toString(a)); int j; for (int gap = a.length/2; gap > 0 ; gap /= 2) { for (int i = gap; i < a.length; i++) { int tmp = a[i]; for (j = i; j >= gap && tmp < a[j-gap] ; j -= gap) { a[j] = a[j-gap]; } a[j] = tmp; } } System.out.println(Arrays.toString(a)); }
以gap=3为例,结合代码:
public void shellSort(){ int[] a = {15, 94, 11, 58, 12, 35, 17, 95, 28, 96, 41, 75, 81};//gap=3之前的数组 System.out.println(Arrays.toString(a)); int j; for (int gap = a.length/2; gap > 0 ; gap /= 2) { for (int i = gap; i < a.length; i++) { int tmp = a[i];//tmp for (j = i; j >= gap && tmp < a[j-gap] ; j -= gap) { a[j] = a[j-gap]; //15, 94, 11, 58, 94, 35, 17, 95, 28, 96, 41, 75, 81 //15, 12, 11, 58, 94, 35, 58, 95, 28, 96, 41, 75, 81 //15, 12, 11, 17, 94, 35, 58, 95, 35, 96, 41, 75, 81 //15, 12, 11, 17, 94, 28, 58, 95, 35, 96, 95, 75, 81 //15, 12, 11, 17, 94, 28, 58, 94, 35, 96, 95, 75, 81 //15, 12, 11, 17, 41, 28, 58, 94, 35, 96, 95, 75, 96 } a[j] = tmp; }
//gap=3之后的数组:[15, 12, 11, 17, 41, 28, 58, 94, 35, 81, 95, 75, 96] } System.out.println(Arrays.toString(a)); }
希尔排序与插入排序不同的是:希尔排序是增量式的不想普通的插入排序一个一个的往前比较,而是按增量进行大间距的移动或交换