快速排序实现方法(剑指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;
}
相关推荐
pen-ai几秒前
【YOLO系列】 YOLOv1 目标检测算法原理详解
算法·yolo·目标检测
2301_7657031422 分钟前
C++中的职责链模式实战
开发语言·c++·算法
StandbyTime30 分钟前
《算法笔记》学习记录-第一章
c++·算法·算法笔记
近津薪荼35 分钟前
优选算法——双指针8(单调性)
数据结构·c++·学习·算法
松☆36 分钟前
Dart 中的常用数据类型详解(含 String、数字类型、List、Map 与 dynamic) ------(2)
数据结构·list
格林威36 分钟前
Baumer相机铆钉安装状态检测:判断铆接是否到位的 5 个核心算法,附 OpenCV+Halcon 的实战代码!
人工智能·opencv·算法·计算机视觉·视觉检测·工业相机·堡盟相机
星空露珠1 小时前
速算24点检测生成核心lua
开发语言·数据库·算法·游戏·lua
历程里程碑1 小时前
Linux15 进程二
linux·运维·服务器·开发语言·数据结构·c++·笔记
happygrilclh1 小时前
高压高频电源的pid算法
算法
格林威2 小时前
Baumer相机铸件气孔与缩松识别:提升铸造良品率的 6 个核心算法,附 OpenCV+Halcon 实战代码!
人工智能·opencv·算法·安全·计算机视觉·堡盟相机·baumer相机