C语言实现快速排序

#include<stdio.h>
void Swap(int arr[], int low, int high)
{
    int temp;
    temp = arr[low];
    arr[low] = arr[high];
    arr[high] = temp;
}

int Partition(int arr[], int low, int high)
{
    int base = arr[low];
    while(low < high)
    {
        while(low < high && arr[high] >= base)
        {
            high --;
        }
        Swap(arr, low, high);  //交换其实是主要判断 arr[high] >= base 是不是大于或者小于基准值
        while(low < high && arr[low] <= base)
        {
            low ++;
        }
        Swap(arr, low, high);  //交换其实是主要判断 arr[low] <= base 是不是大于或者小于基准值
    }
    return low;
}

void QuickSort(int arr[], int low, int high)
{
    if(low < high)
    {
        int base = Partition(arr, low, high);
        QuickSort(arr, low, base - 1);
        QuickSort(arr, base + 1, high); // 在输入测试用例 0 1 3 2 4 5 时,我一直以为输入的high是已经移到最左边,与low一样都是0.后来明白了
                                        //0 是函数内的high,已经被释放,而实际输入的high是一开始的high
                                        //实际上在这个快速排序中high与low的值一直都未改变,改变的只有中间值base.
    }
}

int main()
{
    int n;
    scanf("%d\n",&n);
    int arr[n];
    int i , j;
    for(i = 0; i < n; i ++)
    {
        scanf("%d",&arr[i]);
    }

    QuickSort(arr, 0, n-1);

    for(j = 0; j < n; j ++)
    {
        printf("%4d",arr[j]);
    }
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值