使用min_heap创建优先级队列,当元素数量偶数时会引起问题

时间:2019-04-20 15:11:05

标签: c++

对于一项任务,我一直被要求使用最小堆来创建优先级队列,老实说,我不确定它是什么,但是我的教授一直坚持我只是从基于数组的列表中创建了一个最小堆。两个问题,每当我有偶数个元素时,程序就会冻结在空白输出窗口中,什么也不显示,当我在向函数添加元素时将其实现时,情况也是如此,相关代码如下:

    void heapify(int low, int high) {
        int largeIndex;
        extPersonType temp = list[low];

        largeIndex = 2*low+1;

        while(largeIndex <= high) {
            if(largeIndex < high) {
                if(list[largeIndex].returnKey() > list[largeIndex+1].returnKey()) {
                    largeIndex = largeIndex+1;
                }
                if(temp.returnKey() < list[largeIndex].returnKey()) {
                    break;
                } else {
                    list[low] = list[largeIndex];
                    low = largeIndex;
                    largeIndex = 2*low+1;
                }
            }
        }
        list[low] = temp;
    }

    void buildHeap() {
        for(int index = length; index >= 0; index--) {
            heapify(index, length-1);
        }
    }

这是我在列表功能中添加一项:

void addQueue(const extPersonType &insertItem) {
        int loc;
        if (length == 0) {
            list[length++] = insertItem;
        } else if (length == maxsize) {
            cout << "Cannot Fit In This List" << endl;
        } else {
            loc = seqSearch(insertItem);
            if (loc == -1) {
                list[length++] = insertItem;
            } else {
                cout << "ERROR: Item Already Exists" << endl;
            }
            buildHeap();
        }
    }

0 个答案:

没有答案