下面是我使用基于0的数组构建一个min-heap的程序,该数组具有本书中的标准逻辑。我正在使用2*i+1
用于左子,2*i+2
用于右子,因为它是基于零的数组,但我输出错误。我错过了什么?
#include <iostream>
#include <vector>
#include <algorithm>
using std::vector;
using std::cin;
using std::cout;
class HeapBuilder {
private:
vector<int> data_;
void WriteResponse() const {
for (int i = 0; i < data_.size(); ++i) {
cout << data_[i] << "\n";
}
}
void ReadData() {
int n;
cin >> n;
data_.resize(n);
for (int i = 0; i < n; ++i)
cin >> data_[i];
}
void MinHeapSort(int index)
{
int left = (2 * index) + 1;
int right = (2 * index) + 2;
int smallest;
if (left < data_.size() && data_[left] < data_[index])
smallest = left;
else
smallest = index;
if (right < data_.size() && data_[right] < data_[index])
smallest = right;
if (smallest != index)
{
swap(data_[smallest], data_[index]);
MinHeapSort(smallest);
}
}
void Heapify() {
for (int i = (data_.size() - 1) / 2; i >= 0; i--)
{
MinHeapSort(i);
}
}
public:
void Solve() {
ReadData();
Heapify();
WriteResponse();
}
};
int main() {
std::ios_base::sync_with_stdio(false);
HeapBuilder heap_builder;
heap_builder.Solve();
return 0;
}
答案 0 :(得分:0)
用
替换if (right < data_.size() && data_[right] < data_[index])
if (right < data_.size() && data_[right] < data_[smallest])
这是有效的,愚蠢的错误。