【leetcode】排序算法总结

第 11 章 排序 - Hello 算法动画图解、一键运行的数据结构与算法教程https://www.hello-algo.com/chapter_sorting/

堆排序

cpp 复制代码
#include <iostream>
#include <vector>

using namespace std;

/* 堆的长度为 len ,从节点 i 开始,从顶至底堆化 */
void heapfy(vector<int>& nums, int len, int i) {
    while (true) {
        // 判断节点 i, l, r 中值最大的节点,记为 max
        int left = 2 * i + 1;
        int right = 2 * i + 2;
        int max = i;
        if (left < len && nums[left] > nums[max]) {
            max = left;
        }
        if (right < len && nums[right] > nums[max]) {
            max = right;
        }
        // 若节点 i 最大或索引 l, r 越界,则无须继续堆化,跳出
        if (max == i) {
            break;
        }
        // 交换两节点
        swap(nums[i], nums[max]);
        // 循环向下堆化
        i = max;
    }
}

/* 堆排序 */
void heapSort(vector<int>& nums) {
    int len = nums.size();

    // 建堆操作:堆化除叶节点以外的其他所有节点
    for (int i = len / 2 - 1; i >= 0; --i) {
        heapfy(nums, len, i);
    }
    // 从堆中提取最大元素,循环 n-1 轮
    for (int i = len - 1; i > 0; --i) {
        // 交换根节点与最右叶节点(交换首元素与尾元素)
        swap(nums[i], nums[0]);
        // 以根节点为起点,从顶至底进行堆化
        heapfy(nums, i, 0);
    }
}

int main() {
    vector<int> nums = {5, 2, 4, 6, 8, 1};
    heapSort(nums);
    for (auto& num : nums) {
        cout << num << endl;
    }
}
相关推荐
在猴站学算法4 分钟前
(《统计学习方法》(第2版) 李航)第2章 感知机算法
学习·算法·机器学习·统计学习
Rainmicro8 分钟前
【无标题】
java·数据库·算法
NEFU_Jyj10 小时前
牛客周赛R168
算法
文丑颜不良啊17 小时前
LeetCode2221~2240题目解析
java·leetcode
Navigator_Z18 小时前
LeetCode //C - 1317. Convert Integer to the Sum of Two No-Zero Integers
c语言·算法·leetcode
D e re k ZH18 小时前
C++ 标准库算法全景指南
数据结构·c++·算法
冻柠檬飞冰走茶19 小时前
字母移动游戏题解:贪心求最长可保留连续子串(附 C 实现)
c语言·开发语言·数据结构·算法·动态规划
文丑颜不良啊19 小时前
LeetCode2161~2180题目解析
java·leetcode
雪落漂泊20 小时前
C++算法 二分查找篇(上)
开发语言·c++·算法