Insertion Sort sorting algorithm (direct insertion sort, semi insertion sort, Shell sort)

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/qq_36511401/article/details/102638452

A direct insertion sort.

1 Introduction.

        Direct insertion sort is a simple insertion sort, the basic idea is: the record to be sorted according to their size by one key value is inserted into an already sorted ordered sequence, until all records inserted until the End get a new ordered sequence. For example, a group of records to be sorted are known: 60,71,49,11,24,3,66. Suppose during the sorting process, the first three records by key value increasing order rearranged, constituting an ordered sequence: 49,60,71. The records to be sorted in the fourth recording (i.e., 11) is inserted into the ordered sequence, to obtain a new ordered sequence with four records. First, you should find the insertion position 11, and then insert. The first unit 11 may be placed in the array r [0], this unit is called lookout, and then look for 71 starting from right to left, 11 is less than 71, 71 to a right position, 11 is less than 60, and the right one position 60, 11 is less than 49, 49 to the right again to a position in which the then 11 r [0] comparison value, 11≥r [0], its insertion position is r [1] . 11 assume a value larger than the first r [1]. It should be in the insertion position between the r [1] and r [2], since 60 has been shifted to the right, left out of the recording 11. The position just behind the left by one inserted into the ordered sequence in accordance with the same method. If the number of records n, n-1 times continuously be ordered to complete. 

        Direct insertion sort is stable sort, no additional memory space complexity O (1). Time complexity, best case: O (n) worst case: O (n ^ 2) Average where: O (n ^ 2).

2, step.

    (1) Set lookout r [0], the value to be assigned to insert the record R & lt [0];
    (2) Find the setting position j;
    (3) for the j-th record in the search, the search in an array after the shift, until r [0] .key≥r [j] .key up;
    (4) r [0] inserted position r [j + 1] on.

3, code.

public static void main(String[] args) {
        System.out.println("------开始------");
        //生成生成两份一模一样的随机数组,其中一组用系统自带的方法进行排序,到时候进行验证。
        final int number = 100000;
        int[] sortArray = new int[number];
        int[] sortArrayCopy = new int[number];
        for (int i = 0; i < sortArray.length; i++) {
            sortArray[i] = (int) (Math.random() * number);
        }
        System.arraycopy(sortArray, 0, sortArrayCopy, 0, number);//数组复制
        Arrays.sort(sortArrayCopy);

        //开始排序
        long startTime = System.currentTimeMillis();
        directInsertSort(sortArray);//直接插入排序
        System.out.println("花费时间:" + (System.currentTimeMillis() - startTime));

        //跟系统排序之后数组进行比较,查看是否排序成功。
        if (Arrays.equals(sortArray, sortArrayCopy)) {
            System.out.println("排序成功");
        } else {
            System.out.println("排序失败");
        }
        System.out.println("------结束------");
    }
//直接插入排序 最佳情况:T(n) = O(n)   最坏情况:T(n) = O(n2)   平均情况:T(n) = O(n2)
private static void directInsertSort(int[] array) {
    for (int i = 1; i < array.length; i++) {//n-1轮  第一个无需排序
        int curIndex = i;
        while (curIndex > 0) {
            if (array[curIndex] > array[curIndex - 1]) {
                break;
            }
            int flag = array[curIndex];
            array[curIndex] = array[curIndex - 1];
            array[curIndex - 1] = flag;
            curIndex--;
        }
    }
}

4 results.

Second, the binary insertion sort.

1 Introduction.

        The direct insertion sort to find A [i] to the insertion position using binary comparison method, to obtain binary insertion sort algorithm. When process A [i], A [0] ...... A [i-1] Press the key value has been sorted. The so-called binary comparison, is inserted into A [i], take the A [i-1/2] of the key values ​​A [i] of the key values, if A [i] of the key value is less than A [ i-1/2] a key value, then a [i] can only be inserted between a [i-1/2] [0] to a, it is possible in the a [0] to a [i-1 / continue between 2-1] binary comparison; otherwise only be inserted into A [i-1/2] between A [i-1], it is possible in A [i-1/2 + 1] to A [i continue between -1] binary comparison. So responsible, until finally able to determine the date inserted. Generally between A [k] and A [r] using binary, which is between the nodes A [k + r / 2], after one half comparing to exclude records, may be inserted into the interval is reduced by half, so called binary. Premise execute binary insertion sort is documentation must be stored in order. 

        Binary insertion sort is stable sort, no additional memory space complexity O (1). Time complexity, best case: O (n ^ 2) worst case: where the average O (n ^ 2): O (n ^ 2).

2, step.

        With steps directly into the sort of similar, but to find the insertion point is not the same way. Direct insertion sort is looking forward successively from the last number of ordered regions, and binary insertion sort is to find a way through binary.

    (1) 0 ~ i-1 calculated intermediate point, the intermediate element is compared with the value of the index i, if the element index i is large, description should be inserted between the intermediate element value and the index i just joined , on the contrary, is in a position to a position intermediate the beginning value, so that a very simple binary completed;
    (2) to find the position of insertion inside the respective half of the range, with a constant (1) step narrow, not stop binary range is reduced to 1/2 1/4 1/8 turn quick ....... i-th element is determined to be inserted in any place;
    (3) after determining the location, the entire sequence of the backward and the element inserted into the corresponding position.

3, code.

public static void main(String[] args) {
        System.out.println("------开始------");
        //生成生成两份一模一样的随机数组,其中一组用系统自带的方法进行排序,到时候进行验证。
        final int number = 100000;
        int[] sortArray = new int[number];
        int[] sortArrayCopy = new int[number];
        for (int i = 0; i < sortArray.length; i++) {
            sortArray[i] = (int) (Math.random() * number);
        }
        System.arraycopy(sortArray, 0, sortArrayCopy, 0, number);//数组复制
        Arrays.sort(sortArrayCopy);

        //开始排序
        long startTime = System.currentTimeMillis();
        halveInsertSort(sortArray);//折半插入排序
        System.out.println("花费时间:" + (System.currentTimeMillis() - startTime));

        //跟系统排序之后数组进行比较,查看是否排序成功。
        if (Arrays.equals(sortArray, sortArrayCopy)) {
            System.out.println("排序成功");
        } else {
            System.out.println("排序失败");
        }
        System.out.println("------结束------");
    }
//折半插入排序 最佳情况:T(n) = O(n)   最坏情况:T(n) = O(n2)   平均情况:T(n) = O(n2)
private static void halveInsertSort(int[] array) {
    int flag;
    int low, middle, high;
    for (int i = 1; i < array.length; i++) {//n-1轮
        flag = array[i];
        low = 0;
        high = i - 1;
        while (low <= high) {//最后的情况就是low==high==middle的判断
            middle = (low + high) / 2;
            if (array[i] > array[middle]) {
                low = middle + 1;
            } else {
                high = middle - 1;
            }
        }
        for (int j = i; j > high + 1; j--) {
            array[j] = array[j - 1];
        }
        array[high + 1] = flag;
    }
}

4 results.

Third, the Shell sort.

1 Introduction.

       Hill sorting (Shell's Sort) insertion sort is also known as a "zoom increment sort" (Diminishing Increment Sort), is directly into the Ranking algorithm more efficient improved version. Hill sorting non-stationary sorting algorithm. The method proposed in 1959 due to DLShell named. Shell sort is the subject of pressing the recording packet in increments, the use of direct insertion sort each sorting algorithm; With increment is gradually reduced, more and more keywords each comprising, when reduced to an increment, the entire file is divided into just one set, the algorithm will terminate.

        Hill sorting is not stable sort, no additional memory space complexity O (1). Time complexity, best case: O (nlog ^ 2n) worst case: the average case O (nlog ^ 2n): O (nlogn).

2, step.

        Let's look at the basic Hill sorting step, in which we select incremental gap = length / 2, so as to continue to reduce the incremental gap = gap / 2, which we can use a select incremental sequence represented by { n / 2, (n / 2) / 2 ... 1}, called incremental sequence. Select and proved Hill incremental sequence is a sort of mathematical problems, we have chosen the increment sequence is more commonly used, and it is proposed increment Hill, Hill called incremental, but this is actually not the most incremental sequence excellent. Here we use an example to do an incremental Hill. The entire sequence of records to be sorted first divided into several sub-sequences direct insertion sort, describe specific algorithm: selecting an increment sequence t1, t2, ..., tk, where ti> tj, tk = 1; increments a sequence number k, k times the sequence is sorted; sorting per trip, according to the corresponding increment ti, to be sorted column is divided into several sub-sequences of length m of each sub-table for each direct insertion sort. Only the delta factor is 1, the entire sequence as a processing table, the table length is the length of the entire sequence.

3, code.

public static void main(String[] args) {
        System.out.println("------开始------");
        //生成生成两份一模一样的随机数组,其中一组用系统自带的方法进行排序,到时候进行验证。
        final int number = 100000;
        int[] sortArray = new int[number];
        int[] sortArrayCopy = new int[number];
        for (int i = 0; i < sortArray.length; i++) {
            sortArray[i] = (int) (Math.random() * number);
        }
        System.arraycopy(sortArray, 0, sortArrayCopy, 0, number);//数组复制
        Arrays.sort(sortArrayCopy);

        //开始排序
        long startTime = System.currentTimeMillis();
        shellInsertSort(sortArray);//希尔插入排序
        System.out.println("花费时间:" + (System.currentTimeMillis() - startTime));

        //跟系统排序之后数组进行比较,查看是否排序成功。
        if (Arrays.equals(sortArray, sortArrayCopy)) {
            System.out.println("排序成功");
        } else {
            System.out.println("排序失败");
        }
        System.out.println("------结束------");
    }
//希尔插入排序 最佳情况:T(n) = O(nlog2 n)  最坏情况:T(n) = O(nlog2 n)  平均情况:T(n) =O(nlog2n) 
private static void shellInsertSort(int[] array) {
    int groups = array.length / 2;//增量,一共的组数
    while (groups > 0) {
        //将groups看作1,就会跟直接插入排序的算法一模一样
        for (int i = groups; i < array.length; i++) {//n-1轮  第一个无需排序
            int curIndex = i;
            while (curIndex > groups - 1) {
                if (array[curIndex] > array[curIndex - groups]) {
                    break;
                }
                int flag = array[curIndex];
                array[curIndex] = array[curIndex - groups];
                array[curIndex - groups] = flag;
                curIndex -= groups;
            }
        }
        groups /= 2;
    }
}

4 results.

Guess you like

Origin blog.csdn.net/qq_36511401/article/details/102638452