快速排序
排到最后
当基数在左边时,用a[right]与基数交换;(因为a[rihgt]<a[left])
当基数在右边时,用a[left]与基数交换;
#include<iostream>
using namespace std;
void swap(int &a, int &b)
{
int temp = a;
a = b;
b = temp;
}
void quicksort(int a[],int left, int right)
{
if (left > right)
return;
int pivot = a[left];//left始终在pivot下标。
int i = left+1;//移动的箭头left,right设为i,j;
int j = right;
while (i <= j)//先从左向右排
{
while (i <= j && a[i] <= pivot)
{
++i;
}
while (i<=j && a[j]>pivot)
{
--j;
}
if (i < j)
{
swap(a[i], a[j]);
}
}
a[left] = a[j];
a[j] = pivot;//swap(a[j],a[left])
quicksort(a,left, j - 1);
quicksort(a,j+1, right);
}
int main()
{
int n;
cout << "输入数据个数:" << endl;
cin >> n;
int* a = new int[n];
cout << "输入数据:" << endl;
for (int i= 0; i < n; i++)
{
cin >> a[i];
}
quicksort(a,0, n - 1);
for (int j = 0; j < n; j++)
{
cout << a[j] << " ";
}
return 0;
}