【排序】快速排序

#include<iostream>
using namespace std;

int pnumsrtition(int nums[], int low, int high){
    int pivot_key = nums[low];//用区间的第1个记录作为基准
    while (low < high){//从区间两端交替向中间扫描,直到low=high为止
        while (low < high&&nums[high] >= pivot_key)
            high--;//从右向左扫描,查到第1个关键字小于pivot_key的记录nums[hgih]
        if (low < high)
            nums[low++] = nums[high];//相当于交换nums[low]和nums[high]
        while (low < high&&nums[low] <= pivot_key)
            low++;
        if (low < high)
            nums[high--] = nums[low];
    }
    nums[low] = pivot_key;//基准记录已被最后定位
    return low;
}
void quick_sort(int nums[], int low, int high){
    int pivot; //划分后的基准记录的位置
    if (low < high){
        pivot = pnumsrtition(nums, low, high);//做划分
        quick_sort(nums, low, pivot - 1);
        quick_sort(nums, pivot + 1, high);
    }
}
void print_numsrrnumsy(int nums[], int len){
    for (int i = 0; i < len; i++)
        cout << nums[i] << ' ';
    cout << endl;
}

int main(){
    int nums[] = { 9, 1, 5, 8, 3, 7, 4, 6, 2 };
    int len = sizeof(nums) / sizeof(int);

    quick_sort(nums, 0, len - 1);
    print_numsrrnumsy(nums, len);

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值