/*
*快速排序算法
* 2018年4月9日10:52:26 By 楷谐之力
*/
#include<stdio.h>
#include<stdlib.h>
#define N 8
void printAaary(int *a,int n) //打印数组
{
int i=0;
for(i=0; i<n; i++)
printf("%5d",a[i]);
printf("\n");
}
int sort(int a[],int low,int high)//核心算法
{
int key=a[low],t;
int t1=low,t2=high,i;//测试使用,便于输出每次调用运行结果
static count=0;
while(low<high)
{
while(low<high&&a[high]>=key)
--high;
t=a[low];a[low]=a[high];a[high]=t;
while(low<high&&a[low]<=key)
++low;
t=a[high];a[high]=a[low];a[low]=t;
}
a[low]=key;
printf("第%d次: low=%d ",++count,low);//count计调用sort()函数的次数,用于测试
for(i=t1;i<=t2;i++) //打印输出low-high排序结果
printf("%d ",a[i]) ;
printf("\n");
return low;
}
void quick_sort1(int a[],int low,int high) //快速排序算法
{
int i;
if(low<high)
{
i=sort(a,low,high);
quick_sort1(a,low,i-1);
quick_sort1(a,i+1,high);
}
}
void quick_sort(int a[],int n) //此函数的作用,quick_sort()接口比较人性化
{
quick_sort1(a,0,n-1);
}
int main()
{
int a[N]= {23,45,36,78,12,15,16,69};
printf("\n排序前:\n");
printAaary(a,N);
quick_sort(a,N);
printf("\n排序后:\n");
printAaary(a,N);
}
快速排序算法
最新推荐文章于 2025-06-03 21:16:38 发布