如何解决用于快速排序实现的迭代器与索引
为什么以下快速排序实现在性能上有很大差异?使用迭代器的实现所需时间是使用索引的实现的两倍。同时处于-O0和-03优化。通过mergesort可以看到类似的效果。比较是在std :: vector上运行的。
使用迭代器的快速排序:
template<typename It>
It QuickSortPartitionUtil(It begin,It last) {
auto pivot = last;
auto current = begin;
for(auto it = begin; it < last; ++it) {
if(*it < *pivot) {
std::iter_swap(current,it);
++current;
}
}
std::iter_swap(current,last);
return current;
}
template<typename It>
void QuickSortUtil(It begin,It last) {
if(begin < last) {
auto partition = QuickSortPartitionUtil(begin,last);
QuickSortUtil(begin,std::prev(partition,1));
QuickSortUtil(std::next(partition,1),last);
}
}
template<typename It>
void QuickSort(It begin,It end) {
QuickSortUtil(begin,std::prev(end));
}
使用索引进行快速排序:
template<typename T>
int QuickSortPartition(std::vector<T>& to_sort,int start,int last) {
T pivot = to_sort[last];
int i = start;
for(int j = start; j < last; j++) {
if(to_sort[j] < pivot) {
std::swap(to_sort[i],to_sort[j]);
i++;
}
}
std::swap(to_sort[last],to_sort[i]);
return i;
}
template<typename T>
void QuickSortUtil(std::vector<T>& to_sort,int last) {
if(start < last) {
int p = QuickSortPartition(to_sort,start,last);
QuickSortUtil(to_sort,p-1);
QuickSortUtil(to_sort,p+1,last);
}
}
template<typename T>
void QuickSort(std::vector<T>& to_sort) {
int v = to_sort.size();
QuickSortUtil(to_sort,v-1);
}
主要测试功能:
int main() {
const int size_to_sort{10000};
std::vector<int> to_sort(size_to_sort);
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_real_distribution<> dist(0,size_to_sort);
int duration = 0;
for(int i = 0; i < 1000; i++) {
std::cout << "Iteration: " << i << std::endl;
std::generate(to_sort.begin(),to_sort.end(),[&](){return dist(gen);});
auto start = high_resolution_clock::now();
// QuickSort(to_sort);
QuickSort(to_sort.begin(),to_sort.end());
auto stop = high_resolution_clock::now();
assert(std::is_sorted(to_sort.begin(),to_sort.end()));
duration += duration_cast<microseconds>(stop - start).count();
}
std::cout << "Time taken: " << duration << std::endl;
return 0;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。