c ++我在最大堆中重新调整过程有什么问题?

时间:2016-04-07 19:14:46

标签: heapsort

这是我的第一个stackexchange帖子,所以请温柔:-)我是一名使用c ++学习数据结构的本科生。这是我们实现的头文件(不允许使用stl的堆类,但我们可以使用它的vector类):

template <typename T>
class heap
{
public:
    heap();
    // postcondition: empty heap has been created
    unsigned int size() const;
    // postcondition: number of elements in a heap has been returned
    bool is_empty() const;
    // postcondition: returned whether the heap is empty
    void insert (const T& item);
    // postcondition: item has been added
    void remove();
    // precondition: heap is not empty
    // postcondition: largest item has been removed from the heap
    T max() const;
    // precondition: heap is not empty
    // postcondition: copy of largest element in the heap has been returned
    T& max();
    // precondition: heap is not empty
    // postcondition: access to largest element in the heap has been returned

private:    
    std::vector<T> v;
    unsigned int max_child (unsigned int index) const;
    // precondition: element at index has children
    // postcondition: index of the larger child has been returned
    // if there is only 1 child - index of that child has been returned
};

我添加了这个帮助成员函数(在私有部分中)

//template <typename T>
void swap_up(const T& item, std::vector<int> v);

这是我对insert函数的实现:

template <typename T>
void heap<T>::insert (const T& item)
// postcondition: item has been added
{
    v.push_back(item);
    if(v.size() > 1){
        swap_up(item, v);
    }
}

我知道如果一切都已经完成,我不应该调用swap_up函数,但我现在并不关心。我关心这个功能里面发生了什么。这是我的swap_up函数:

template <typename T>
void heap<T>::swap_up(const T& item, std::vector<int> v){

    unsigned int index = v.size()-1;
    unsigned int parent_index = (index-1)/2;
    //unsigned int value;
    T value;

    while(item > v[parent_index]){

        //if(item > v[parent_index]){
            value = v[parent_index];
            v[parent_index] = item;
            v[index] = value;
        //}

        if(parent_index > 0){
            index = parent_index;
            parent_index = (index-1)/2;
        }
    }
}

这是我的测试代码:

#include <iostream>
#include "heap.h"
//#include "priority_queue.h"

using namespace std;

int main() {
    heap<int> h1;
    h1.insert(40);
    h1.insert(50);
    h1.insert(60);
    h1.insert(70);
    h1.insert(80);

    int max = h1.max();
    cout << "The max is " << max << endl;

    return 0;
}

当我运行此代码时,最大值始终为40.我不明白为什么,因为我认为我从平衡堆的末端移动到适当的停止点的算法非常可靠。我在这里错过了什么吗?提前谢谢。

1 个答案:

答案 0 :(得分:0)

我想我看到了我的问题。每次插入我都会进入一个新的向量。这可以解释为什么原始向量总是将第一个值显示为最大值 - 它永远不会收到另一个值!我想通过访问heap.h中的私有向量变量来改变我的代码以继续使用我的swap_up()函数,但我还没有弄清楚如何这样做。