Java's seven major sortings: Hill sorting (also a kind of insertion sort)

(1) Basic idea

Also known as the "shrinking increment method". First select an integer, divide all the records in the file to be sorted into multiple groups, put all the records with distance into the same group, and sort the records in each group. Then take and repeat the above grouping and sorting work. When =1 is reached, all records are sorted in the same group.

 

(2) Code implementation

public static void shellSort(int[] array) {
        int gap = array.length;
        while (gap > 1) {
            shell(array, gap);
            gap /= 2;
        }
        //将整体进行插入排序
        shell(array,1);
    }
    public static void shell(int[] array,int gap) {
        for (int i = gap; i < array.length; i++) {
            int tmp = array[i];
            int j  = i-gap;
            for (; j >= 0 ; j-=gap) {
                if (array[j] > tmp) {
                    array[j+gap] = array[j];
                } else {
                    break;
                }
            }
            array[j+gap] = tmp;
        }
    }

(3) Feature summary

1. Hill sort is an optimization of direct insertion sort.

2. When gap > 1, it is pre-sorted to make the array closer to order. When gap == 1, the array is already nearly ordered, so it will be fast.

3. The time complexity of Hill sorting is difficult to calculate because there are many ways to value gaps, which makes it difficult to calculate. Therefore, the time complexity of Hill sorting given in some trees is not fixed.

4. In this article, gap=gap/2 is taken, the time complexity is O(N^1.3~N^1.5), and the space complexity is O(1). This is an unstable sorting method.

Guess you like

Origin blog.csdn.net/m0_56911648/article/details/130659697