C++ 优化气泡排序-我遗漏了什么?
我试图了解气泡排序算法可能的优化方法。我知道有更好的分类方法,但我只是好奇 为了测试效率,我使用std::chrono。该程序对10000个长整数数组进行30次排序,并打印平均排序时间。在每次迭代中随机选取数字(最多10000个)。以下是没有优化的代码:C++ 优化气泡排序-我遗漏了什么?,c++,algorithm,sorting,optimization,bubble-sort,C++,Algorithm,Sorting,Optimization,Bubble Sort,我试图了解气泡排序算法可能的优化方法。我知道有更好的分类方法,但我只是好奇 为了测试效率,我使用std::chrono。该程序对10000个长整数数组进行30次排序,并打印平均排序时间。在每次迭代中随机选取数字(最多10000个)。以下是没有优化的代码: #include <iostream> #include <ctime> #include <chrono> using namespace std; int main() { //bubb
#include <iostream>
#include <ctime>
#include <chrono>
using namespace std;
int main() {
//bubble sort
srand(time(NULL));
chrono::time_point<chrono::steady_clock> start, end;
const int n = 10000;
int i,j, last, tests = 30,arr[n];
long long total = 0;
bool out;
while (tests-->0) {
for (i = 0; i < n; i++) {
arr[i] = rand() % 1000;
}
j = n;
start = chrono::high_resolution_clock::now();
while(1){
out = 0;
for (i = 0; i < j - 1; i++) {
if (arr[i + 1] < arr[i]) {
swap(arr[i + 1], arr[i]);
out = 1;
}
}
if (!out) {
break;
}
//j--;
}
end = chrono::high_resolution_clock::now();
total += chrono::duration_cast<chrono::nanoseconds>(end - start).count();
cout << "Remaining :"<<tests << endl;
}
cout << "Average :" << total / static_cast<double>(30)/1000000000<<" seconds"; // tests(30) + nanosec -> sec
cin.sync();
cin.ignore();
return 0;
}
#include <iostream>
#include <ctime>
#include <chrono>
using namespace std;
int main() {
//bubble sort
srand(time(NULL));
chrono::time_point<chrono::steady_clock> start, end;
const int n = 10000;
int i,j, last, tests = 30,arr[n];
long long total = 0;
bool out;
while (tests-->0) {
for (i = 0; i < n; i++) {
arr[i] = rand() % 1000;
}
j = n;
start = chrono::high_resolution_clock::now();
while(1){
out = 0;
for (i = 0; i < j - 1; i++) {
if (arr[i + 1] < arr[i]) {
swap(arr[i + 1], arr[i]);
out = 1;
last = i;
}
}
if (!out) {
break;
}
j = last + 1;
}
end = chrono::high_resolution_clock::now();
total += chrono::duration_cast<chrono::nanoseconds>(end - start).count();
cout << "Remaining :"<<tests << endl;
}
cout << "Average :" << total / static_cast<double>(30)/1000000000<<" seconds"; // tests(30) + nanosec -> sec
cin.sync();
cin.ignore();
return 0;
}
#包括
#包括
#包括
使用名称空间std;
int main(){
//气泡排序
srand(时间(空));
计时:时间点开始、结束;
常数n=10000;
int i,j,last,tests=30,arr[n];
长总计=0;
发出嘘声;
同时(测试-->0){
对于(i=0;i 好吧……问题是这个问题可能没有正确或错误的答案
首先,当您仅比较10000个元素时,您不能真正将其称为效率测试。请尝试比较更多的元素-可能是500000个(尽管您可能需要为此计算数组动态)
其次,可能是编译器。编译器通常会尝试优化一些东西,以便程序执行更平稳、更快。您需要运行大约十分之一秒,才能为函数获得稳定、具有代表性的时钟时间。太低的第一次缓存效应和时钟粒度主导了读取。这就是我所做的:用于(i=0;iI尝试了100000个元素,在第一篇文章中发布了结果。仍然会得到奇怪的结果。我认为这不是编译器的错误,因为逻辑上更好的优化比简单的j--1需要更长的时间。只需关闭编译器上的优化,然后比较结果。它可能根本不是优化。除非您的数组几乎已排序—它可能需要比第一个版本更多的工作,您必须在每次迭代中至少执行2个额外的赋值,如果您的数组几乎未排序,它将执行更多的赋值,几乎一直到数组的末尾。