• 普通插入排序与成对插入排序


    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;

  • 相关阅读:
    POJ2104&&HDU2665(静态区间第K小)
    HDU4763
    js 获取视频的第一帧
    hadoop 集群配置
    redis_cli 批量删除
    vmware centos 7 更新vmware-tools
    php计算两个整数的最大公约数常用算法小结
    centOS 7 配置NAT模式
    centOS配置NAT模式
    show table status 获取表的信息
  • 原文地址:https://www.cnblogs.com/wzyxidian/p/5215094.html
Copyright © 2020-2023  润新知