【C语言】【十大排序算法】快速排序

利用分治思想:
1、从数组中取出一个数,称为基数(pivot)
2、遍历数组,将比基数大的数字放在其右,比基数小的放在其左。遍历完成后,数组将被分为左右2个区域。
2、将左右两个区域视为2个数组,重复之前步骤,直到排序完成。
在实现过程中,可以借助双指针:

#include <stdio.h>

void quickSort(int* nums, int start, int end) {
    if (start > end) {
        return;
    }
    int left = start;
    int right = end;
    // 快速排序 Step1: 取出一个数,作为基数pivot
    int pivot = nums[start]; // 这里取第一个数为基数
    // 快速排序 Step2: 遍历数组,将比基数大的数放在其右,比基数小的放在其左
    while (start < end) {
        while (start < end && nums[end] >= pivot) {
            end--; // 对数组倒序遍历
        }
        // 因为此时end位置的数比基数要小,因此需要将小的数放在其左(star位置,可能并不是数组的最左)。
        nums[start] = nums[end]; // 不用担心原来的start处的数,原来的数被暂存在pivot中了
        while (start < end && nums[start] <= pivot) {
            start++; // 对数组顺序遍历
        }
        // 因为start位的元素比基数要大,因此需要将这个大的数放在其右(end位置,并不是数组的最右)。
        nums[end] = nums[start]; // 不用担心原来的end处的数,原来的数被存在开头了,相当于挪动了

    }
    nums[start] = pivot;
    // 此時start和end都移动到中间了,以此为分隔点,继续对左右数组进行快速排序
    quickSort(nums,left,start-1);
    quickSort(nums,start+1,right);
}
int main() {
    printf("快速排序算法(Quick Sort Algorithm)\n");
    int nums[] = {81, 94, 11, 96, 12, 35, 17, 95, 28, 58, 41, 75, 15};
    printf("排序前:");
    for (int i = 0; i < 13; ++i) {
        printf("%d ",nums[i]);
    }
    quickSort(nums, 0, 12); // 要求传入start和end指针
    printf("\n排序后:");
    for (int i = 0; i < 13; ++i) {
        printf("%d ",nums[i]);
    }
    return 0;
}

运行结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

碧波bibo

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值