快速排序实现方法(剑指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;
}
相关推荐
郝学胜-神的一滴2 小时前
Effective Python 条款36:优雅拼装迭代器与生成器
开发语言·数据结构·人工智能·python·numpy·scikit-learn
AvocadoZeroOneOI3 小时前
B4500 [GESP202603 三级] 凯撒密码 详细解题报告
c++·算法
cjz38995 小时前
双指针技巧:覆盖式双指针(原地覆盖)
算法
console.log('npc')8 小时前
Python 学习教程 · 第4课:数据结构
数据结构·python·学习
橘子139 小时前
【高级数据库】关系代数基本概念
算法
电科_银尘20 小时前
【大模型算法与工程 15】手写Self-Attention:Q、K、V与缩放点积
算法
郝学胜-神的一滴1 天前
Effective STL 条款03:容器中的对象复制要廉价且正确
开发语言·数据结构·c++·算法·rpc·stl
秋天的怀念_David1 天前
算法一千零一夜 · 第三十三夜 · 跳表
java·程序人生·算法
Pniubi1 天前
力扣21合并两个有序链表
算法·leetcode·职场和发展
AIgorithmGEEK1 天前
std::unordered_map 与 std::unordered_set:接口、算法技巧与权衡 (速查)
c++·算法·哈希表·负载因子·桶·unordered_map·unordered_set