[英]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.