手写快排两要素:
- 递归
- 小左大右
#include<iostream>
using namespace std;
void Swap(int& a, int& b){
int aa = a,bb=b;
b = aa;
a = bb;
return;
}
int Partition(int data[], int start, int end){
if(data==nullptr || start<0 || start > end){
cout << "input invalid.";
exit(0);
}
int small = start;
for (int i = start; i < end; i++)
{
if(data[i]<data[end]){
if(i!=small)
Swap(data[i], data[small]);
++small;
}
}
Swap(data[small], data[end]);
return small;
}
void QuickSort(int data[],int start,int end){
if(start==end)
return;
int index = Partition(data, start, end);
if(index>start)
QuickSort(data, start, index - 1);
if(index<end)
QuickSort(data, index+1, end);
}
int main()
{
int a[] = {1, 4, 2,3,5,8,10,0,12};
QuickSort(a, 0, 8);
for (int i = 0; i < 9;i++){
cout << a[i] << " ";
}
}
Partition函数选中最后一个元素为基准,其他小于它的元素放前面