Sas*_*hra 0 c++ sorting algorithm stl c++11
我已经编写了一个代码来在 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;
}
Run Code Online (Sandbox Code Playgroud)
如果你想查看头文件的内容:
#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 */
Run Code Online (Sandbox Code Playgroud)
输出中的向量是完全未排序的;我尝试过基于范围的 for 循环和迭代器,但没有任何帮助。请为我提供一些解决方案或想法,我完全糊涂了。