min-heap 基于零的数组 C++

min-heap with zero based array C++

下面是我的程序,它使用基于 0 的数组和书中的标准逻辑来构建 min-heap。我对左 child 使用 2*i+1,对右 child 使用 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;
}

已将 if (right < data_.size() && data_[right] < data_[index]) 替换为

if (right < data_.size() && data_[right] < data_[smallest])

成功了,愚蠢的错误。