C语言-快速排序算法

递归函数实现快速排序算法

#include <stdio.h>
#include <stdlib.h>

int QKPass(int r[],int low,int high)
{
    int x;
    x = r[low];
    while(low<high)
    {
        while(low<high && r[high]>=x)
        {
            high--;
        }
        if(low<high)
        {
            r[low] = r[high];
            low++;
        }
        while(low<high && r[low]<x)
        {
            low++;
        }
        if(low<high)
        {
            r[high] = r[low];
            high--;
        }
    }
    r[low]=x;
    return low;
}

void QKSort(int r[],int low,int high)
{
    int pos;
    if(low<high)
    {
        pos = QKPass(r,low,high);
        QKSort(r,low,pos-1);
        QKSort(r,pos+1,high);
    }
}
int* QuickSort(int *array,int begin,int end)
{
    if(begin>end)
        return NULL;//递归函数返回条件
    int x = array[begin];
    int i = begin,j = end;
    int temp;
    while(i != j)
    {

        while((array[j] >= x)&&(j > i))
            j--;  //从最右侧开始寻找比X小的数
        while((array[i] <= x)&&(j > i))
            i++;  //从最左侧开始寻找比X大的数
        if(j>i)
        {
            temp = array[i];//两个数交换
            array[i] = array[j];
            array[j] = temp;
        }
    }
    array[begin] = array[j];
    array[j] = x;
    //此时 i==j ,完成左侧数都比X小,右侧数比X大
    QuickSort(array,begin,i-1);//递归调用,左侧再排序
    QuickSort(array,i+1,end);//递归调用,右侧再排序

    return array;
}
/******************************************/
int main()
{
    int i;
    int a[] = {4,1,2,3,4,5,6,9,8,7,5,54,76,89};
    QKSort(a,0,13);
    for(i=0;i<14;i++)
        printf("%d  ",a[i]);
    return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值