Sorting algorithm --- Hill sorting (java version)

Hill sort

principle

First divide the table to be sorted into a number of records separated by a certain "increment" to form a sub-table, and directly insert each sub-table separately. When the elements in the entire table are basically in order, perform the whole record again Direct insertion sort. Hill sort mainly solves the problem of direct insertion sort because the elements in the table are basically ordered, but some elements are far away from themselves, which causes more exchanges.

The sorting process of Hill sorting is implemented as shown in the
Insert picture description here
code

public class ShellSort {
    
    
    public static void main(String[] args) {
    
    
        shellSort();
    }

    //交换法实现shell排序
    public static void shellSort() {
    
    
        int[] arr = {
    
    8, 9, 1, 7, 2, 3, 5, 4, 6, 0};
        int temp = 0;
        //gap代表步长
        for (int gap = arr.length / 2; gap > 0; gap /= 2) {
    
    
            // i是arr[gap]之后的元素arr[5]-arr[9]
            for (int i = gap; i < arr.length; i++) {
    
    
                // 遍历各组中所有的元素(共gap组,每组有个元素), 步长gap
                for (int j = i - gap; j >= 0; j -= gap) {
    
    
                    // 如果当前元素大于加上步长后的那个元素,则交换
                    if (arr[j] > arr[j + gap]) {
    
    
                        temp = arr[j];
                        arr[j] = arr[j + gap];
                        arr[j + gap] = temp;
                    }
                }
            }
            System.out.println(Arrays.toString(arr));
        }
    }

    //对交换式的希尔排序进行优化->移位法
    public  static void shellSort2() {
    
    
        int[] arr = {
    
    8, 9, 1, 7, 2, 3, 5, 4, 6, 0};
        for (int gap = arr.length/2; gap >0; gap/=2) {
    
    
            // 从第gap个元素,逐个对其所在的组进行直接插入排序
            for (int i = gap; i < arr.length; i++) {
    
    
                int j = i;
                int temp = arr[j];
                if (arr[j] < arr[j - gap]) {
    
    
                    while (j - gap >= 0 && temp < arr[j - temp]) {
    
    
                        //移动
                        arr[j] = arr[j - gap];
                        j -= gap;
                    }
                    //当退出while后,就给temp找到插入的位置
                    arr[j] = temp;
                }
            }
        }
    }
}

1. Time complexity of Hill sorting

In the worst case, the time complexity of Hill sorting is O(n^2).

2. Space complexity of Hill sorting

Only a constant number of auxiliary units are used, so the space complexity is O(1).

3. Stability of Hill Sorting

When the records of the same key are divided into different subtables, the relative order between them may be changed. Therefore, Hill sorting is an unstable sorting method.

Guess you like

Origin blog.csdn.net/qq_33626996/article/details/113178160