#include <iostream>
#include <vector>
#include <algorithm>
#include <iomanip>
#include <limits>
#include <random>
using namespace std;
int Partition(vector<int> & vec, int low, int high)
{
std::uniform_int_distribution<int> distribution(low + 1, high);
std::default_random_engine generator;
swap(vec[low], vec[distribution(generator)]);
int pivot = vec[low];
while (low < high)
{
while (low < high && vec[high] >= pivot)
{
high--;
}
vec[low] = vec[high]; // 不能high--,因为high这个位置将来要用于交换。
while (low < high && vec[low] <= pivot)
{
low++;
}
vec[high] = vec[low];
}
vec[low] = pivot;
return low;
}
void QuickSort(vector<int> & vec, int low, int high)
{
if (low < high)
{
int index = Partition(vec, low, high);
QuickSort(vec, low, index - 1);
QuickSort(vec, index + 1, high);
}
}
void QuickSort(vector<int> & vec)
{
int len = vec.size();
if (len <= 1)
{
return ;
}
else
{
QuickSort(vec, 0, len - 1);
}
}
int main()
{
std::vector<int> v(10);
std::generate(std::begin(v), std::end(v), [](){static int i = 10; return (i--);});
std::cout << "Before Sort : " << std::endl;
std::for_each(std::begin(v), std::end(v), [](int x){std::cout << std::setw(3) << x;});
std::cout << std::endl;
QuickSort(v);
std::cout << "After Sort : " << std::endl;
std::for_each(std::begin(v), std::end(v), [](int x){std::cout << std::setw(3) << x;});
std::cout << std::endl;
return 0;
}
【C++代码】快速排序
于 2019-09-09 19:34:08 首次发布