排序优化时间

Sort Optimisation time

本文关键字:时间 优化 排序      更新时间:2023-10-16

我有两个排序:

void sort1(std::vector<int> &toSort)
{
    for(VintIter i=toSort.begin(); i!=toSort.end(); i++)
    {
        for (VintIter j =(toSort.end()-1); j != i; --j)
        {
            if (*(j - 1) > *(j))
            {
                std::iter_swap(j - 1, j);
            }
        }
    }
}
 void sort2(std::vector<int> &toSort)
    {
        for(int i= 0; i<(toSort.size()-1); i++)
        {
            int minElem=i,maxElem=i+1;
            if(toSort[minElem]>toSort[maxElem])
            {
                std::swap(toSort[minElem],toSort[maxElem]);
            }
            while(minElem>0 && toSort[minElem]<toSort[minElem-1])
            {
                std::swap(toSort[minElem],toSort[minElem-1]);
                minElem--;
            }
            while(maxElem<(toSort.size()-1) && toSort[maxElem]>toSort[maxElem+1])
            {
                std::swap(toSort[maxElem],toSort[maxElem+1]);
                maxElem++;
            }
        }
    }

我使用queryperformancfrequency和QueryPerformanceCounter来获得这些时间。对于1000个元素的随机向量,对于sort1返回20.3,对于sort2返回5.4。这是可以的…但当我试图得到排序数组的结果时,最好的情况是toSort向量已经排序了,结果有点奇怪。对于sort1是12.234,对于sort2是0.0213。对于10000个元素,sort1是982.069,而sort2是0.2!

我有一个断言来比较向量是否排序。我用的是Windows 7和Windows 8的最新版本。对于i7-5700 HQ和i5-6300U.

这只是我创造更好的东西的练习,没有实现。这都是我的想法,所以我不想使用std::sort.

我的问题是:为什么第二个算法给我~0时间与10000个元素?

第一个在任何情况下都具有的复杂度。

而在排序的情况下,第二个算法是线性的:

toSort[minElem] < toSort[minElem - 1]toSort[maxElem] > toSort[maxElem+1]总是false,因此您的内循环立即中断。