快速排序实现方法(剑指offer思路)

快速排序思想

从参与排序的数组中,选择一个数,把小于这个数的放在左边,大于这个数的放在右边,然后递归操作。

实现算法思路

  • 选择最后一个当作参考值,
  • 使用small索引当作比这个数小的下标值
  • 遍历数组,如果小于参考值,small+1,如果i和small不相等,交换i和small对应下标的数据
  • small增加1,和最后一个值交换
  • 递归调用比small小的前一部分
  • 递归调用比small小的后一部分
cpp 复制代码
#include <iostream>
#include <vector>

using namespace std;
void quickSort(vector<int>& arr, int start, int end)
{
    if((start >= end))
    {
        return;
    }

    int small = start - 1;
    for(int index = start; index < end; ++index)
    {
        if(arr[index] < arr[end])
        {
            ++small;
            if(index != small)
            {
                std::swap(arr[index], arr[small]);
            }
        }
    }

    ++small;
    std::swap(arr[small], arr[end]);
    
    quickSort(arr, start, small-1);
    quickSort(arr, small+1, end);
}

int main(int argc, char** argv)
{
    std::vector<int> arr{1,3,5,7,8,2,6};
    quickSort(arr, 0, arr.size()-1);
    std::copy(arr.begin(), arr.end(), std::ostream_iterator<int>(cout," "));
    std::cout<<std::endl;
    return 0;
}
相关推荐
土司大王24 分钟前
LeetCode hot100——两两交换链表中的节点
算法·leetcode·职场和发展
41 分钟前
数据结构第一课:复杂度解析
数据结构
大熊背2 小时前
树莓派IspPipeline LSC模块原理详解
算法·lsc·isppipeline·mesh lsc
zander2582 小时前
LeetCode 300. 最长递增子序列
算法·leetcode·深度优先
欧叶冲冲冲2 小时前
Python常见数据结构的CRUD(LeetCode高频版速查)
数据结构·python·leetcode
祖力553 小时前
Linux应用软件编程:目录IO与framebuffer
linux·运维·算法·framebuffer·目录io
名字还没想好☜3 小时前
Go 用 slices/maps 标准库泛型函数:告别手写 Contains、Sort、去重(Go 1.21)
开发语言·后端·算法·golang·go
地平线开发者3 小时前
【模型轻量化专题】深度学习模型为什么需要轻量化
算法
_Narcissus_3 小时前
链表算法题和静态链表
数据结构·c++·笔记·算法·链表·ai·力扣
Lyyaoo.3 小时前
【普通数组】【中等】除了自身以外数组的乘积
数据结构·算法·leetcode