【CS.AL】八大排序算法 —— 快速排序全揭秘:从基础到优化

2024-06-09 11:04

本文主要是介绍【CS.AL】八大排序算法 —— 快速排序全揭秘:从基础到优化,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

在这里插入图片描述

文章目录

    • 1. 快速排序简介
      • 1.1 定义
      • 1.2 时间复杂度
      • 1.3 相关资源
    • 2. 最优的Partition算法 🔥
      • 2.1 Introsort简介
      • 2.2 过程示例
    • 3. 非递归快速排序
      • 3.1 实现
    • 4. 递归快速排序
      • 4.1 实现
    • 5. 有问题的Partition
      • 5.1 实现
    • 6. 三中位数主元选择
      • 6.1 实现
    • 7. 总结

1. 快速排序简介

1.1 定义

快速排序:快速排序也采用分治策略,选择一个基准元素,将数组分成比基准小和比基准大的两部分,再对两部分递归地进行排序。快速排序的平均时间复杂度为O(n log n),是目前应用广泛的排序算法之一。

1.2 时间复杂度

  • 最坏情况:O(n²)
  • 平均情况:O(n log₂n)
  • 最佳情况:O(n log₂n)

1.3 相关资源

912. 排序数组 - 力扣(LeetCode)

2. 最优的Partition算法 🔥

2.1 Introsort简介

Introsort(内排序)从快速排序开始作为主要排序算法。在最坏情况下(例如,数组已经排序或接近排序),快速排序可能退化为O(n²)时间复杂度。为了避免快速排序的最坏情况,Introsort引入了一个最大递归深度。当递归深度超过这个阈值时,算法切换到堆排序或归并排序,以确保更好的最坏情况性能。

template <typename Tp>
int partition(vector<Tp>& nums, int lIdx, int rIdx) {int randomIndex = lIdx + rand() % (rIdx - lIdx + 1);std::swap(nums[randomIndex], nums[rIdx]);Tp pivot = nums[rIdx];int lBoundary = lIdx;int rBoundary = rIdx - 1;for(; ; ++lBoundary, --rBoundary){for (; lBoundary <= rBoundary && nums[lBoundary] < pivot; ++lBoundary) {}for (; lBoundary <= rBoundary && nums[rBoundary] > pivot; --rBoundary) {}if (lBoundary > rBoundary) {break;}std::swap(nums[lBoundary], nums[rBoundary]);}std::swap(nums[rIdx], nums[lBoundary]);return lBoundary;
}

2.2 过程示例

  • 假设 nums = [7, 3, 5, 1, 2, 6, 4],随机选择的pivot下标为5,即6与最右的4交换,得到 nums = [7, 3, 5, 1, 2, 4, 6]
  • 分区指针起始如图:left (lIdx) -> 7, 3, 5, 1, 2, 4 <- right (rIdx), 6(pivot)
  • 左指针移动到第一个大于或等于主元的元素(即7),右指针移动到第一个小于或等于主元的元素(为4):left (lIdx) -> 7, 3, 5, 1, 2, 4 <- right (rIdx), 6(pivot)
  • 交换左右指针处的元素:left (lIdx) -> 4, 3, 5, 1, 2, 7 <- right (rIdx), 6(pivot)
  • 继续该过程,直到左右指针相遇:4, 3, 5, 1, 2 <- right (rIdx), left (lIdx) -> 7, 6(pivot)
  • 将枢轴元素(当前位于右指针处)与左指针处的元素交换(6和7交换)。

3. 非递归快速排序

3.1 实现

template <typename Tp>
void quickSort(vector<Tp>& nums) {std::stack<std::pair<int, int>> stack;stack.push(std::make_pair(0, nums.size() - 1));while (!stack.empty()) {std::pair<int, int> current = stack.top();stack.pop();int lIdx = current.first;int rIdx = current.second;if (lIdx < rIdx) {int boundary = partition(nums, lIdx, rIdx);stack.push(std::make_pair(lIdx, boundary - 1));stack.push(std::make_pair(boundary + 1, rIdx));}}
}

4. 递归快速排序

4.1 实现

template <typename Tp>
void qSortRecursion(vector<Tp>& nums, const int& lIdx, const int& rIdx) {if (lIdx < rIdx) {int boundary = partition(nums, lIdx, rIdx);qSortRecursion(nums, lIdx, boundary - 1);qSortRecursion(nums, boundary + 1, rIdx);}
}template <typename Tp>
void quickSort(vector<Tp>& nums) {qSortRecursion(nums, 0, nums.size() - 1);
}

5. 有问题的Partition

5.1 实现

大量重复元素会超时:

template <typename Tp>
int partition(vector<Tp>& nums, int lIdx, int rIdx) {// 较为有序时, 避免超时int randIdx = lIdx + rand() % (rIdx - lIdx + 1);std::swap(nums[randIdx], nums[rIdx]);int pivot = nums[rIdx];int boundary = lIdx;for (int idx = lIdx; idx < rIdx; ++idx) {if (nums[idx] < pivot) {std::swap(nums[idx], nums[boundary]);++boundary;}}std::swap(nums[boundary], nums[rIdx]); // pivotreturn boundary;
}

通过内排序Introsort修复:

template <typename Tp>
void quickSort(vector<Tp>& nums) {double recThreshold = log10(nums.size()) / log10(2);int recDepth = 0;std::stack<std::pair<int, int>> stack;stack.push(std::make_pair(0, nums.size() - 1));while (!stack.empty()) {++recDepth;if (recDepth >= recThreshold) {heapSort(nums);break;}std::pair<int, int> current = stack.top();stack.pop();int lIdx = current.first;int rIdx = current.second;if (lIdx < rIdx) {int boundary = partition(nums, lIdx, rIdx);stack.push(std::make_pair(lIdx, boundary - 1));stack.push(std::make_pair(boundary + 1, rIdx));}}
}

6. 三中位数主元选择

6.1 实现

template <typename Tp>
int choosePivot(vector<Tp>& nums, int lIdx, int rIdx) {int mid = lIdx + (rIdx - lIdx) / 2;if (nums[lIdx] > nums[mid]) {std::swap(nums[lIdx], nums[mid]);}if (nums[mid] > nums[rIdx]) {std::swap(nums[mid], nums[rIdx]);}if (nums[lIdx] > nums[mid]) {std::swap(nums[lIdx], nums[mid]);}return mid;
}template <typename Tp>
int partition(vector<Tp>& nums, int lIdx, int rIdx) {int pivotIdx = choosePivot(nums, lIdx, rIdx);std::swap(nums[pivotIdx], nums[rIdx]);Tp pivot = nums[rIdx];int lBoundary = lIdx;int rBoundary = rIdx - 1;for(; ; ++lBoundary, --rBoundary){for (; lBoundary <= rBoundary && nums[lBoundary] < pivot; ++lBoundary) {}for (; lBoundary <= rBoundary && nums[rBoundary] > pivot; --rBoundary) {}if (lBoundary > rBoundary) {break;}std::swap(nums[lBoundary], nums[rBoundary]);}std::swap(nums[rIdx], nums[lBoundary]);return lBoundary;
}

7. 总结

快速排序作为一种现代化的排序算法,通过分治策略和递归实现,高效地解决了大多数排序问题。使用最优的Partition算法和三中位数主元选择可以有效优化快速排序的性能,并避免最坏情况的出现。

这篇关于【CS.AL】八大排序算法 —— 快速排序全揭秘:从基础到优化的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1044991

相关文章

从基础到高级详解Python数值格式化输出的完全指南

《从基础到高级详解Python数值格式化输出的完全指南》在数据分析、金融计算和科学报告领域,数值格式化是提升可读性和专业性的关键技术,本文将深入解析Python中数值格式化输出的相关方法,感兴趣的小伙... 目录引言:数值格式化的核心价值一、基础格式化方法1.1 三种核心格式化方式对比1.2 基础格式化示例

redis-sentinel基础概念及部署流程

《redis-sentinel基础概念及部署流程》RedisSentinel是Redis的高可用解决方案,通过监控主从节点、自动故障转移、通知机制及配置提供,实现集群故障恢复与服务持续可用,核心组件包... 目录一. 引言二. 核心功能三. 核心组件四. 故障转移流程五. 服务部署六. sentinel部署

从原理到实战解析Java Stream 的并行流性能优化

《从原理到实战解析JavaStream的并行流性能优化》本文给大家介绍JavaStream的并行流性能优化:从原理到实战的全攻略,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的... 目录一、并行流的核心原理与适用场景二、性能优化的核心策略1. 合理设置并行度:打破默认阈值2. 避免装箱

Python实战之SEO优化自动化工具开发指南

《Python实战之SEO优化自动化工具开发指南》在数字化营销时代,搜索引擎优化(SEO)已成为网站获取流量的重要手段,本文将带您使用Python开发一套完整的SEO自动化工具,需要的可以了解下... 目录前言项目概述技术栈选择核心模块实现1. 关键词研究模块2. 网站技术seo检测模块3. 内容优化分析模

Java实现复杂查询优化的7个技巧小结

《Java实现复杂查询优化的7个技巧小结》在Java项目中,复杂查询是开发者面临的“硬骨头”,本文将通过7个实战技巧,结合代码示例和性能对比,手把手教你如何让复杂查询变得优雅,大家可以根据需求进行选择... 目录一、复杂查询的痛点:为何你的代码“又臭又长”1.1冗余变量与中间状态1.2重复查询与性能陷阱1.

Python内存优化的实战技巧分享

《Python内存优化的实战技巧分享》Python作为一门解释型语言,虽然在开发效率上有着显著优势,但在执行效率方面往往被诟病,然而,通过合理的内存优化策略,我们可以让Python程序的运行速度提升3... 目录前言python内存管理机制引用计数机制垃圾回收机制内存泄漏的常见原因1. 循环引用2. 全局变

从基础到进阶详解Python条件判断的实用指南

《从基础到进阶详解Python条件判断的实用指南》本文将通过15个实战案例,带你大家掌握条件判断的核心技巧,并从基础语法到高级应用一网打尽,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一... 目录​引言:条件判断为何如此重要一、基础语法:三行代码构建决策系统二、多条件分支:elif的魔法三、

Python WebSockets 库从基础到实战使用举例

《PythonWebSockets库从基础到实战使用举例》WebSocket是一种全双工、持久化的网络通信协议,适用于需要低延迟的应用,如实时聊天、股票行情推送、在线协作、多人游戏等,本文给大家介... 目录1. 引言2. 为什么使用 WebSocket?3. 安装 WebSockets 库4. 使用 We

Python多线程实现大文件快速下载的代码实现

《Python多线程实现大文件快速下载的代码实现》在互联网时代,文件下载是日常操作之一,尤其是大文件,然而,网络条件不稳定或带宽有限时,下载速度会变得很慢,本文将介绍如何使用Python实现多线程下载... 目录引言一、多线程下载原理二、python实现多线程下载代码说明:三、实战案例四、注意事项五、总结引

Python多线程应用中的卡死问题优化方案指南

《Python多线程应用中的卡死问题优化方案指南》在利用Python语言开发某查询软件时,遇到了点击搜索按钮后软件卡死的问题,本文将简单分析一下出现的原因以及对应的优化方案,希望对大家有所帮助... 目录问题描述优化方案1. 网络请求优化2. 多线程架构优化3. 全局异常处理4. 配置管理优化优化效果1.