QuickSort
Program not like Math, has few but vast ways.
Program Pearls Series aims to find "the way".
算法珠玑系列,旨在写出SoTA的算法代码,这种实现,实现那唯一的实现
QuickSort
#include<iostream>
#include<vector>
using namespace std;
typedef int T;
void swap(vector<T>& v, int index1, int index2)
{
T temp = v[index1];
v[index1] = v[index2];
v[index2] = temp;
}
int partition(vector<T>& v, int left, int right)
{
int smaller = left;
for (int i = left; i < right; ++i)
{
if (v[i] < v[right])
{
swap(v, i, smaller);
++smaller;
}
}
// already find all smaller number
swap(v, smaller, right);
return smaller;
}
void quickSort(vector<T>& v, int left, int right)
{
if(left < right)
{
int pi = partition(v, left, right);
quickSort(v, left, pi-1);
quickSort(v, pi+1, right);
}
}
int main()
{
vector<T> v = {1,2,3,5,0,34,1,39,13909, 888};
quickSort(v, 0, v.size()-1);
for (T e : v) std::cout << e << "\n";
}
以上即是快速排序。