STL堆排序&时间复杂度分析

1. 逻辑&时间复杂度分析

pop 和 initialize 的时间复杂度请参考:
[DSAAinC++] 大根堆的pop&remove&initialize

将数组初始化为一棵 max heap, 时间复杂度为 \(O(n)\).
max heap 的 root 必然是所有 node 中最大的.
排序就是利用这个性质, 将 max heap 的 root 不断 pop 出来, 存入结果数组.
每次 pop 完又会构成一个新的 max heap, 一共 pop \(n\) 次.
因此最坏情况下 pop 总步数为:

\[\sum_{i=1}^{n}{\log{i}} = \log(n!) \leq n\log{n} \]

因此时间复杂度为:

\[O(n) + O(n\log{n}) = O(n\log{n}) \]

2. 代码实现(STL)

#include <iostream>
#include <algorithm>
#include <vector>

int main()
{
    std::vector<int> vec{ 10,4,6,26,3,54,7,8,23,2 };
    std::make_heap(vec.begin(), vec.end(), std::greater<int>());
    std::sort_heap(vec.begin(), vec.end());
    for (auto i : vec) { printf("%d ", i); }
    std::cin.get();
}

Reference | Data Structures, Algoritms, and Applications in C++, Sartaj Sahni

posted @ 2022-08-06 12:40  JamesNULLiu  阅读(84)  评论(0编辑  收藏  举报