排序优化时间
Sort Optimisation time
我有两个排序:
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个元素?
第一个在任何情况下都具有n²
的复杂度。
而在排序的情况下,第二个算法是线性的:
toSort[minElem] < toSort[minElem - 1]
和toSort[maxElem] > toSort[maxElem+1]
总是false
,因此您的内循环立即中断。
相关文章:
- 为什么 std::chrono 在测量循环和编译器优化的并行 OpenMP 的执行时间时不起作用?
- 如何优化C++键值程序以获得更快的运行时间
- 优化了第 n 个质数执行时间的 c++ 函数
- 使用LTO静态链接的可执行文件(链接时间优化):如何使用以前构建的库进行制作
- 在NDK中启用链接时间优化时,链接器错误
- C1001反量时间的错误(无优化)
- 如何使用MINGW-W64通过链接时间优化构建QT
- 优化时间性能Unordered_map C
- 在Windows上使用GCC的链接时间优化构建wxWidgets DLL时出错
- C 控制台应用程序;在牙科诊所情况下,时间优化了队列
- gcc 5.1 中的链接时间优化是否足以放弃内联简单函数
- 如何进行llvm链接时间优化
- 库中的链接时间优化
- 生成排列的时间优化(竞争编程)
- Clang链接时间优化与替换的操作员新的原因不匹配的自由()/删除在valgrind
- 是否可以启用链接时间优化,同时仅禁用某些函数的严格混叠
- 链接时间优化与多线程支持冲突
- Mac上的g++链接时间优化-编译器/链接器错误
- 链接时间优化vs.项目内联;每种方法的局限性
- LLVM 和安装时间优化