繁体   English   中英

Heapify 方法对于最大堆无法正常工作

[英]Heapify method is not working properly for max heap

我正在准备数据结构和算法期末考试。 我正在努力研究我们本学期学到的所有数据结构,并自行编写程序以帮助我为期末考试做准备。 我现在正在处理最大堆,其中包括插入(使用堆化)和检索最大值。 我被困在父母和孩子的堆积/交换上。 似乎 heapify 不起作用,因为我按照插入数字的顺序取回了一个数组。 这是我到目前为止所拥有的。

private int getLeftChildIndex(int index)
    {
        return (2*index + 1);
    }
    private int getLeftChildValue(int index)
    {
        return heap[2*index + 1];
    }


    private int getRightChildIndex(int index)
    {
        return (2*index + 2);
    }
    private int getRightChildValue(int index)
    {
        return heap[2*index + 2];
    }

    private int getParentIndex(int index)
    {
        return ((int) Math.ceil((index - 2)/2));
    }

    private void swap(int child, int parent)
    {
        int temp = heap[parent];
        heap[parent] = heap[child];
        heap[child] = temp;
    }

    private void insert(int num)
    {
        heap[heapSize] = num;
        heapSize++;
        int index = heapSize - 1;
        while (getParentIndex(index) > 0 && heap[index] > heap[getParentIndex(index)])
        {
            swap(index, getParentIndex(index));
            index = getParentIndex(index);
        }
    }
 public static void main(String[] args)
    {
        HeapTest heap = new HeapTest();
        heap.insert(15);
        heap.insert(5);
        heap.insert(10);
        heap.insert(30);
    }

例如,它只是给出了 [15,5,10,30] 形式的数组。 这个最大堆数组的形式应该是 [30,15,10,5]

我期待这个:[15,5,10,30] -> [15,30,10,5] -> [30,15,10,5]

任何人都可以提供一些关于为什么插入的堆化部分不起作用的见解吗?

谢谢!!

我可以看到几个问题。

  1. 考虑Math.ceil((index - 2)/2)将为索引 3 返回什么。这将返回 0 而不是 1,因为/2是 integer 操作。 将其更改为/2.0将修复它。 或者更简单的方法是使用 integer 算法和(index - 1) / 2 ,这样更清晰,更高效。

  2. getParentIndex(index) > 0意味着您将忽略索引 0 处的根节点 - 目前您的代码永远不会交换该项目。 更改为>=将修复它。

很可能还有其他问题,但这些是 2 我可以通过检查看到。 单元测试或交互式调试都会发现这些问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM