用于快速排序实现的迭代器与索引

问题描述

为什么以下快速排序实现在性能上有很大差异?使用迭代器的实现所需时间是使用索引的实现的两倍。同时处于-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 (将#修改为@)

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...