快速排序C语言版
/**快速排序
*用递归调用实现快速排序
*/
#include "stdio.h"
typedef int type;
void Swap(type &a,type &b) //交换函数
{
type temp;
temp=a;
a=b;
b=temp;
}
void quickSort(type a[],int low,int high) //快速排序
{
int l=low; //记住最小下标
int h=high; //记住最大下标
type pivot=a[low]; //将最小下标的元素设为枢纽值
while(low<high)
{
while(low<high&&a[high]>pivot) //直到找到一个比pivot大的元素,然后交换
high--;
Swap(a[low],a[high]);
while(low<high&&a[low]<pivot) //直到找到一个比pivot小的元素,然后交换
low++;
Swap(a[low],a[high]);
}
int flag=low; //进行一次排序,此时low=high,二者指向同一个值:pivot
if(l<low) //必须加上此限制条件,因为原数组可能已经是非递减数组
quickSort(a,l,flag-1); //重排比pivot小的部分,递归调用quickSort函数
if(h>high) //必须加上此限制条件,因为原数组可能已经是非递减数组
quickSort(a,flag+1,h); //重排比pivot大的部分,递归调用quickSort函数
}
void main()
{
int i;
type a[8]={3,1,5,8,7,4,2,6};
printf("排序前的数组为:"); //输出排序前的数据
for(i=0;i<8;i++)
printf("%d ",a[i]);
printf("\n");
quickSort(a,0,7);
printf("排序后的数组为:"); //输出排序后的数据
for(i=0;i<8;i++)
printf("%d ",a[i]);
printf("\n");
}