zoukankan      html  css  js  c++  java
  • 普通插入排序与成对插入排序

    for (int i = left, j = i; i < right; j = ++i)

    {
                        int ai = a[i + 1];
                        while (ai < a[j]) {
                            a[j + 1] = a[j];
                            if (j-- == left) {
                                break;
                            }
                        }
                        a[j + 1] = ai;
                    }

    成对插入排序,提高了插入排序的性能,同时可以插入两个数值

    do {
                        if (left >= right) {
                            return;
                        }
                    } while (a[++left] >= a[left - 1]);

                    /*
                     * Every element from adjoining part plays the role
                     * of sentinel, therefore this allows us to avoid the
                     * left range check on each iteration. Moreover, we use
                     * the more optimized algorithm, so called pair insertion
                     * sort, which is faster (in the context of Quicksort)
                     * than traditional implementation of insertion sort.

        ​    ​    ​    ​ * 具体执行过程:上面的do-while循环已经排好的最前面的数据

        ​    ​    ​    ​*(1)将要插入的数据,第一个值赋值a1,第二个值赋值a2,

        ​    ​    ​    ​*(2)然后判断a1与a2的大小,使a1要大于a2

        ​    ​    ​    ​*(3)接下来,首先是插入大的数值a1,将a1与k之前的数字一一比较,直到数值小于a1为止,把a1插入到合适的位置,注意:这里的相隔距离为2

        ​            *(4)接下来,插入小的数值a2,将a2与此时k之前的数字一一比较,直到数值小于a2为止,将a2插入到合适的位置,注意:这里的相隔距离为1

                    *(5)最后把最后一个没有遍历到的数据插入到合适位置

                     */
                    for (int k = left; ++left <= right; k = ++left) {
                        int a1 = a[k], a2 = a[left];

                        if (a1 < a2) {
                            a2 = a1; a1 = a[left];
                        }
                        while (a1 < a[--k]) {
                            a[k + 2] = a[k];
                        }
                        a[++k + 1] = a1;

                        while (a2 < a[--k]) {
                            a[k + 1] = a[k];
                        }
                        a[k + 1] = a2;
                    }
                    int last = a[right];

                    while (last < a[--right]) {
                        a[right + 1] = a[right];
                    }
                    a[right + 1] = last;
                }
                return;

  • 相关阅读:
    Partition算法及其应用
    [LeetCode 405.] Convert a Number to Hexadecimal
    LeetCode Path Sum 系列
    组合数计算
    (一) go 实现的基于REST的Web服务
    (十)原型模式
    (一)排序
    (九)装饰模式
    (八)适配器模式
    (七)外观模式
  • 原文地址:https://www.cnblogs.com/wzyxidian/p/5215094.html
Copyright © 2011-2022 走看看