
希尔排序将整个数组根据间隔h分割为若干个子数组,他们相互穿插在一起,每一次排序时,分别对每一个子数组进行排序。当h=3时,希尔排序将整个数组分为交织在一起的三个子数组。如图所示。其中,所有的方形为一个子数组,所有的圆形、三角形分别组成另外两个子数组。每次排序时总是交换间隔为h的两个元素。

在每一组排序完成后,可以递减h的值,进行下一轮更加精细的排序。直到h=1,此时等价于一次插入排序。
希尔排序的主要优点:即使是一个较小的元素在数组的末尾,由于每次元素移动都以h为间隔进行,因此数组末尾的小元素可以在很少的交换次数下,就被置换到最接近元素最终的位置。
希尔排序的串行实现:
public static void shellSort(int [] arr){
//计算出最大的 h 值
int h = 1;
while (h <= arr.length/3){
h = h * 3 + 1;
}
while ( h > 0 ){
for ( int i = h ; i < arr.length ; i ++){
if ( arr[i]< arr [i-h]) {
int tmp = arr[i];
int j = i - h ;
while (j >=0 && arr[j]>tmp ){
arr[j + h] = arr [j];
j -= h ;
}
arr[j + h] = tmp ;
}
}
//计算出下一个 h 值
h =( h-1 )/3;
}
}
public static void main(String[] args){
int[] art = {1, 5, 3, 2, 7, 6, 1};
shellSort(art);
System.out.println(Arrays.toString(art));
}
[1, 1, 2, 3, 5, 6, 7]
希尔排序的并行实现:
static ExecutorService pool = Executors.newCachedThreadPool();
public static class ShellSortTask implements Runnable {
int i = 0 ;
int h = 0;
CountDownLatch l;
public ShellSortTask(int i,int h, CountDownLatch l) {
this.i = i;
this.h = h;
this.l = l;
}
@Override
public void run(){
if ( arr[i] < arr[i-h] ){
int tmp = arr[i];
int j = i - h ;
while (j >= 0 && arr[j] > tmp) {
arr[j + h] = arr[j];
j -= h;
}
arr[j+h] = tmp ;
}
l.countDown();
}
public static void pShellSort(int [] arr) throws InterruptedException {
//计算出最大的 h 值
int h = 1;
CountDownLatch latch = null;
while ( h <= arr.length/3 ) {
h = h * 3 + 1;
}
while (h > 0) {
System.out.println(" h =" + h);
if (h >= 4) {
latch = new CountDownLatch(arr.length - h);
}
for (int i = h; i < arr.length; i++) {
//控制线程数量 h>=4时使用并行线程,否则退化成传统的插入排序
if (h >= 4) {
pool.execute(new ShellSortTask(i, h, latch));
} else {
if (arr[i] < arr[i - h]) {
int temp = arr[i];
int j = i - h;
while (j >= 0 && arr[j] > temp) {
arr[j + h] = arr[j];
j -= h;
}
arr[j + h] = temp;
}
/*System.out.println(Arrays.toString(arr));*/
}
}
//等待线程排序完成,进入下一次排序
assert latch != null;
latch.await();
//计算出下一个h值;每次递减后、递减h的值
h = (h - 1)/3;
}
}
}
public static void main(String[] args) throws InterruptedException {
int[] art = {1, 5, 3, 2, 7, 6, 1};
ShellSortTask.pShellSort(art);
System.out.println(Arrays.toString(art));
}
[1, 1, 2, 3, 5, 6, 7]