手写C++快速排序

手写堆排序:https://blog.csdn.net/weixin_42887343/article/details/119930432

1 快速排序的原理

在这里插入图片描述

2 快速排序函数

int getIndex(vector<double>& arr, int low, int high)
{
    double tmp = arr[low]; // 首个元素作为基准数据
    while (low < high)
    {
        while (low < high && arr[high] >= tmp)  high --;    // 当队尾的元素大于等于基准数据时,向前挪动high指针
        arr[low] = arr[high];                               // 如果队尾元素小于tmp了,需要将其赋值给low
        while (low < high && arr[low] <= tmp)   low ++;     // 当队首元素小于等于tmp时,向前挪动low指针
        arr[high] = arr[low];                               // 当队首元素大于tmp时,需要将其赋值给high
    }// 跳出循环时low和high相等,此时的low或high就是tmp的正确索引位置
    //由原理部分可以很清楚的知道low位置的值并不是tmp,所以需要将tmp赋值给arr[low]
    arr[low] = tmp;
    return low; // 返回tmp的正确位置
}

void quickSort(vector<double>& arr, int low, int high)
{
    if (low < high)
    {
        int index = getIndex(arr, low, high);	// 找寻基准数据的正确索引
        quickSort(arr, low, index - 1);         //左边递归
        quickSort(arr, index + 1, high);        //右边递归
    }
}

上面排序对象是vector,如果需要排序int数组或者其他数组,只需要换几个地方便可解决。

  1. int getIndex(vector& arr, int low, int high) 改为 int getIndex(int arr[], int low, int high)
  2. double tmp = arr[low]; 改为 int tmp = arr[low];
  3. void quickSort(vector& arr, int low, int high) 改为 void quickSort(int arr[], int low, int high)

3 demo代码(leetcode中的考试题)

   double getAdmissionLine(int k, vector<double>& scores) 
    {
        quickSort(scores,0,scores.size()-1);	//快速排序
        if(k > scores.size())
            k = 0;
        else
            k = scores.size()-k;
        return scores[k];
    }

4 快速排序性能

在这里插入图片描述

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值