排序算法-希尔排序

  希尔排序也被称为“缩小增量排序”,其基本原理如下:先将待排序的数组元素分为多个子序列,使得每个子序列的元素个数相对较小,然后对各个子序列分别进行直接插入排序,待整个待排序序列“基本有序后”,最后再对所有元素进行一次直接插入排序。

public class Sort {

    private static void sort4(int[] a) {
        for(int h = a.length / 2; h > 0; h /= 2) {
            for(int i = h; i < a.length; ++i) {
                int temp = a[i], j = i;
                while(j >= h && a[j - h] > temp)
                {
                    a[j] = a[j - h];
                    j -= h;
                }
                a[j] = temp;
            }
        }

    }

    public static void main(String[] args) {
        int[] a = {36, 27, 48, 12, 25, 65, 43, 57};
        sort4(a);
        print(a);
    }

    private static void print(int[] a) {
        System.out.print("从小到大希尔排序:");
        for(int i : a)
            System.out.print(i + " ");
        System.out.println();
    }

}

打印结果:

从小到大希尔排序:12 25 27 36 43 48 57 65

文章目录