快速排序

快速排序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");
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值