建完堆之后堆顶是几
把乱序数组 17、24、15、13、23 就地整理成大顶堆。运行下面这段程序:
#include <algorithm>
#include <iostream>
#include <string>
#include <utility>
#include <vector>
using namespace std;
void sift_down(vector<int>& h, int i, int n) {
while (true) {
int big = i;
int l = 2 * i + 1;
int r = 2 * i + 2;
if (l < n && h[l] > h[big]) big = l;
if (r < n && h[r] > h[big]) big = r;
if (big == i) return;
swap(h[i], h[big]);
i = big;
}
}
void build_heap(vector<int>& h) {
int n = (int)h.size();
for (int i = n / 2 - 1; i >= 0; i--) sift_down(h, i, n);
}
int main() {
vector<int> h = {17, 24, 15, 13, 23};
build_heap(h);
cout << h[0] << endl;
}
(本题用 g++ -std=c++17 -O0 编译。)
全部评论