【发布时间】:2014-10-26 03:17:06
【问题描述】:
我已经实现了两种算法,用于从最高到最低对元素进行排序。
第一个在真实 RAM 模型上花费二次时间,第二个花费 O(n log(n)) 时间。 第二个使用优先级队列来减少。
这里是时序,是上述程序的输出。
- 第一列是随机整数数组的大小
- 第二列是 O(n^2) 技术的时间(以秒为单位)
-
第三列是 O(n log(n)) 技术的时间,以秒为单位
9600 1.92663 7.58865 9800 1.93705 7.67376 10000 2.08647 8.19094
尽管在复杂性上存在很大差异,但对于所考虑的数组大小,第 3 列大于第 2 列。为什么会这样? C++的优先队列实现慢吗?
我在 Windows 7、Visual Studio 2012 32 位上执行了这段代码。
这是代码,
#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <algorithm>
#include <vector>
#include <queue>
#include <Windows.h>
#include <assert.h>
using namespace std;
double time_slower_sort(vector<int>& a)
{
LARGE_INTEGER frequency, start,end;
if (::QueryPerformanceFrequency(&frequency) == FALSE ) exit(0);
if (::QueryPerformanceCounter(&start) == FALSE ) exit(0);
for(size_t i=0 ; i < a.size() ; ++i)
{
vector<int>::iterator it = max_element( a.begin() + i ,a.end() ) ;
int max_value = *it;
*it = a[i];
a[i] = max_value;
}
if (::QueryPerformanceCounter(&end) == FALSE) exit(0);
return static_cast<double>(end.QuadPart - start.QuadPart) / frequency.QuadPart;
}
double time_faster_sort(vector<int>& a)
{
LARGE_INTEGER frequency, start,end;
if (::QueryPerformanceFrequency(&frequency) == FALSE ) exit(0);
if (::QueryPerformanceCounter(&start) == FALSE ) exit(0);
// Push into the priority queue. Logarithmic cost per insertion = > O (n log(n)) total insertion cost
priority_queue<int> pq;
for(size_t i=0 ; i<a.size() ; ++i)
{
pq.push(a[i]);
}
// Read of the elements from the priority queue in order of priority
// logarithmic reading cost per read => O(n log(n)) reading cost for entire vector
for(size_t i=0 ; i<a.size() ; ++i)
{
a[i] = pq.top();
pq.pop();
}
if (::QueryPerformanceCounter(&end) == FALSE) exit(0);
return static_cast<double>(end.QuadPart - start.QuadPart) / frequency.QuadPart;
}
int main(int argc, char** argv)
{
// Iterate over vectors of different sizes and try out the two different variants
for(size_t N=1000; N<=10000 ; N += 100 )
{
// initialize two vectors with identical random elements
vector<int> a(N),b(N);
// initialize with random elements
for(size_t i=0 ; i<N ; ++i)
{
a[i] = rand() % 1000;
b[i] = a[i];
}
// Sort the two different variants and time them
cout << N << " "
<< time_slower_sort(a) << "\t\t"
<< time_faster_sort(b) << endl;
// Sanity check
for(size_t i=0 ; i<=N-2 ; ++i)
{
assert(a[i] == b[i]); // both should return the same answer
assert(a[i] >= a[i+1]); // else not sorted
}
}
return 0;
}
【问题讨论】:
-
从堆中弹出的是
O(log N),而不是O(1)。 -
除其他事项外,您需要记住每个算法都有一个 K - 恒定开销 - 这可能非常大。 “大 O” 数字仅在限制范围内有效。
-
您正在使用几乎相同大小的集合。如果要检查算法复杂性,则需要更大范围的大小。
-
你开启优化了吗?
-
@smilingbuddha:在顶部,应该有一个下拉框,允许您在调试和发布之间进行选择。选择发布。
标签: c++ sorting heapsort selection-sort