数据结构之快速排序

本文介绍了一个使用C语言实现的快速排序算法。通过选取枢轴并进行分区操作来递归地对数组进行排序。该实现包括定义数组、创建分区函数及快速排序函数,并在主函数中演示了如何输入数据并调用排序函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >



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

int a[1000];

int partition(int * a, int low, int high) {
    int pivotKey;
    pivotKey = a[low];  //将枢轴记录取出来,此位置就空出来了
    while (low < high) {
        while (low < high && a[high] >= pivotKey)
            high--;
        if (low < high)
            a[low++] = a[high];

        while (low < high && a[low] <= pivotKey)
            low++;
        if (low < high)
            a[high--] = a[low];
    }
    a[low] = pivotKey;
    return low;
}

void quickSort(int * a, int s, int t) {
    int pivotLoc;
    if (s < t) {    //若长度为1,则不需要排序了
        pivotLoc = partition(a, s, t);
        quickSort(a, s, pivotLoc - 1);
        quickSort(a, pivotLoc + 1, t);
    }
}

void main() {
    int n, i;
    while (scanf("%d", &n) == 1) {
        for (i = 0; i < n; i++)
            scanf("%d", &a[i]);

        quickSort(a, 0, n-1);

        for (i = 0; i < n-1; i++)
            printf("%d ", a[i]);
        printf("%d\n", a[i]);
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值