快速排序实现方法(剑指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;
}
相关推荐
青少儿编程课堂12 小时前
第十八届蓝桥杯青少组图形化真题:校园分形雪花绘制解析(全国青少年信息素养大赛·电子学会图形化考级冲刺)
c++·python·算法·bfs·信息学竞赛
geovindu13 小时前
python: KNeighborsClassifier K
开发语言·后端·python·算法
让我们一起加油好吗15 小时前
【数据结构】线段树详解
数据结构·c++·算法·线段树·洛谷
路灯中转站15 小时前
数据结构C语言版(什么是数据类型)
数据结构
凌冰_15 小时前
数据结构 - 队列(五)
数据结构·算法·软件工程
让我们一起加油好吗16 小时前
【数据结构】ST 表
数据结构·c++·算法·动态规划·洛谷·st表
让我们一起加油好吗17 小时前
【算法刷题】LeetCode 力扣 Hot 100 刷题记录
数据结构·c++·算法·leetcode·面试·笔试
lisw051 天前
稀疏算法概述!
算法·机器人·无人机
YLCHUP1 天前
【括号匹配+dp优化】题解:双端括号(brackets)_动态规划_状态优化_数学建模_贪心_性质挖掘_STLmap_C++算法竞赛
数据结构·c++·笔记·算法·数学建模·贪心算法·动态规划