快排是一个步稳定的排序方法。
#include<stdio.h>
int n;
int swapPartition(int a[],int low,int high)//一趟划分算法如下
{
a[0]=a[low];
while(low<high)
{
while(low<high&&a[high]>=a[0])//往前跳过比支点大的,寻找比支点小的
{
high--;
}
if(low<high)
{
a[low]=a[high];
low++;
}
while(low<high&&a[low]<=a[0])//往后跳过比支点记录小的,寻找比支点大的
{
low++;
}
if(low<high)
{
a[high]=a[low];
high--;
}
}
a[low]=a[0];
return low;
}
void swapQuikSort(int a[],int s,int t)
{
if(s<t)
{
int i=swapPartition(a,s,t);
swapQuikSort(a,s,i-1);
swapQuikSort(a,i+1,t);
}
}
int main()
{
scanf("%d",&n);
int a[n+1];
int i=0;
for(i=1;i<=n;i++)
{
scanf("%d",&a[i]);
}
swapQuikSort(a,1,n);
int j=0;
for(j=1;j<=n;j++)
{
printf("%d ",a[j]);
}
printf("\n");
return 0;
}
简单测试结果: