快速排序
基本思想
- 任取一个元素(如:第一个)为中心
- 所有比它小的元素一律前放,比它大的元素一律后放,形成左右两个子表
- 对各子表重新选择中心元素并按上述规则调整,直至每个表中的元素的只剩一个
代码
#include<iostream>
using namespace std;
int Partition(int num[], int low, int high)
{
num[0] = num[low];
int pivot = num[low];
while(low < high)
{
while(low < high && num[high] >= pivot) --high;
num[low] = num[high];
while(low < high && num[low] <= pivot) ++low;
num[high] = num[low];
}
num[low] = num[0];
return low;
}
void Qsort(int num[], int low, int high)
{
if(low < high)
{
int pivotloc = Partition(num, low, high);
Qsort(num, low, pivotloc-1);
Qsort(num, pivotloc+1, high);
}
}
int main()
{
int n;
cin >> n;
int num[n+1];
for(int i=1;i<=n;i++) cin >> num[i];
Qsort(num, 1, n);
for(int i=1;i<=n;i++) cout << num[i] << " ";
return 0;
}