我拥有一个std::vector<Sequence>
中的13721057
个元素。我需要对这个向量进行排序并获取前25个元素。我认为,由于可以在O(N)
中构建堆,因此弹出25个元素(每个元素都是O(logN)
)一定比在O(NlogN)
中对整个向量进行排序更快。
但是,当我计时代码时:
clock_t tStart = clock();
sort(mostFrequent.begin(), mostFrequent.end(), greater<Sequence>());
printf("Time taken: %.2fs\n", (double)(clock() - tStart)/CLOCKS_PER_SEC);
与
clock_t tStart = clock();
make_heap(mostFrequent.begin(), mostFrequent.end());
printf("Time taken: %.2fs\n", (double)(clock() - tStart)/CLOCKS_PER_SEC);
整个向量排序似乎更快。为什么呢?
std::sort
和std::make_heap
同时提供相同的比较函数? - Adrian McCarthy