将此解释为循环片段

时间:2012-10-25 06:58:33

标签: java

这里我们有一个二进制堆的数组实现的片段。我想要一些帮助,看看这个for循环在伪代码中意味着什么:

public void insert (Anytype x) { 
    int hole = ++currentSize; //currentSize is the size of the array
    for (array[0] = x; x.compareTO(array[hole / 2]) < 0; hole /= 2)
        array[hole] = array[hole / 2];
    array[hole] = x;
}

我似乎无法理解这个for循环是如何工作的。谢谢。

编辑填补了空缺

2 个答案:

答案 0 :(得分:1)

转换为二进制堆的数组可以如下所示

         [elem 0] <-- put the inserted element here? (why? a precaution perhaps?)

         [element 1]...
    [element2] [ element3 ]  
[elem4][elem5] [elem6][elem7]  
[x][x] [x][x]  [x][XX] ... <-- unoccupied

代码通过将索引孔除以2来传播到每个节点的父节点。 然后它将父节点移动到当前节点,如果父节点>当前节点。

我认为有一个错误......至少这不是典型的解决方案,其中一个将插入的元素作为最后一个非占用的“洞”并从该位置向上移动....

正确的方法是开始比较最后一个元素的父元素并迭代到root。没有必要交换,但是在索引“漏洞”结束的地方,这是最终放置新元素的适当位置。 (典型的解决方案是将'X'放在最后一个位置并且交换,但这样效率很低。)而且for循环中的第一次初始化也是不必要的。

无论如何,索引算法在省略索引0时有效。

答案 1 :(得分:0)

我不太确定你在寻找什么,但这里有:

compareTo返回一个int。如果x小于y,则x.compareTo(y)返回负数。

所以代码粗略地这样做:

for( set the first pos in the array to x; if x is less than array[hole/2]; hole/=2){
   array[hole] = array[hole/2];

Set your arr[final val of hole] to x
相关问题