簡體   English   中英

最小堆,基於零的數組C ++

[英]min-heap with zero based array C++

下面是我的程序,使用書中的標准邏輯,使用基於0的數組構建最小堆。 由於其基於零的數組,我對左子代使用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;
}

替換為if (right < data_.size() && data_[right] < data_[index])

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

那行得通,愚蠢的錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM