[英]std::sort function is not sorting a vector, and I don't know why?
我已经编写了一个代码来在 C++ 中实现快速排序算法,它正在工作,但 std::sort() 函数根本不工作。 请向我解释原因。
#include "header.h"
using namespace std;
using namespace std::chrono;
bool myfunction (int i,int j) { return (i<j); }
int Partition(vector<int>& A, int start, int end){
int pivot_idx = (rand() % (end - start + 1)) + start;
Xswap(A[pivot_idx], A[end]);
int pivot = A[end];
int P_index = start;
for(int i=start; i < end; i++){
if(A[i] <= pivot){
Xswap(A[i], A[P_index]);
P_index++;
}
}
Xswap(A[P_index], A[end]);
return P_index;
}
void Qsort(vector<int>& A, int start, int end){
if(start < end){
int middle = Partition(A, start, end);
Qsort(A, start, middle-1);
Qsort(A, middle+1, end);
}
}
void quick_sort(void){
srand(time(NULL));
int n;
cin >> n;
vector<int> v;
v.reserve(n);
//v.shrink_to_fit();
for(int i=0; i<n; i++)
v[i] = rand() % 1000;
/*for(int i=0; i<n; i++)
cout << v[i] << " ";
cout << endl << endl;*/
auto start = high_resolution_clock::now();
//Qsort(v, 0, n-1);
sort(v.begin(), v.end(), myfunction);
auto stop = high_resolution_clock::now();
auto duration = duration_cast<microseconds>(stop - start);
for(int i=0; i<n; i++)
cout << v[i] << " ";
cout << endl;
cout << duration.count() << endl;
}
如果你想查看头文件的内容:
#ifndef HEADER_H
#define HEADER_H
#include <cstdlib>
#include <algorithm>
#include <iostream>
#include <vector>
#include <chrono>
#include <time.h>
void bble_sort(void);
void improved_bble_sort(void);
void quick_sort(void);
void ins_sort(void);
void Qsort(std::vector<int>& A, int start, int end);
template <typename T>
void Xswap(T& a, T& b);
#endif /* HEADER_H */
输出中的向量是完全未排序的; 我尝试过基于范围的 for 循环和迭代器,但没有任何帮助。 请为我提供一些解决方案或想法,我完全糊涂了。
std::vector::reserve
是对容器的提示,以启用更少的重新分配。 它实际上并没有使v[5]
有效。 相反,使用std::vector::resize()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.