快速排序c++实现
#include <iostream>
#include <ctime>
#include <vector>
using std::vector;
void quicksort(vector<int>& vec,int low,int high)
{
if(low >= high)
return;
int i = low;
int j = high;
int tmp = vec[i];
while(i < j)
{
while(i < j && vec[j] >= tmp)
j--;
vec[i] = vec[j];
while(i < j && vec[i] <= tmp)
i++;
vec[j] = vec[i];
}
vec[i] = tmp;
quicksort(vec,low,i-1);
quicksort(vec,i+1,high);
}
int main()
{
vector<int> vec;
const int n = 20;
srand(time(0));
for (int i = 0; i < n; ++i) {
vec.push_back(rand()%100+1);
}
std::cout << "before sort:" << std::endl;
for (int ele : vec) {
std::cout << ele << ",";
}
std::cout << std::endl;
quicksort(vec,0,n-1);
std::cout << "after sort:" << std::endl;
for (int ele : vec) {
std::cout << ele << ",";
}
std::cout << std::endl;
return 0;
}