为什么这个快速排序算法看起来比 std::sort 更快?我已经检查过以确保它实际上正在对数组进行排序。我还用具有相同迭代次数的空心 for 循环替换了两个排序调用,以测试计时基准并在那里检查所有内容。
我还想知道我可以对快速排序进行哪些调整以允许它递归更多次。也许某种可变内存管理?
#include <iostream>
#include <vector>
#include <algorithm>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <chrono>
using namespace std;
void quickSort(int*, int);
void fillRandom(int*, int,int b2);
int main() {
//setup arrays
int size = 100000;
auto myints = new int[size];
auto myints2 = new int[size];
fillRandom(myints, size,10000);
std::copy(myints, myints + size, myints2);
//measurement 1
auto t1 = std::chrono::high_resolution_clock::now();
quickSort(myints, size);
auto t2 = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::microseconds>(t2 - t1).count();
std::cout << endl << "Execution 1 …Run Code Online (Sandbox Code Playgroud) 我想知道在地图中的最后一个元素之后分配值 1 是否是一种不好的做法,如下例所示。
using namespace std;
auto chances = map<int, int>{};
chances[0] = 20;
chances[1] = 10;
chances[2] = 30;
int last = 0;
for (auto it = chances.begin(); it != chances.end();) {
last = it->second;
(++it)->second += last;
}
Run Code Online (Sandbox Code Playgroud)
此外,在 for 循环中检查变量比终止函数更快(循环的这一部分称为什么?)