码:
import java.util.Arrays;
class Heapify {
int[] array;
Heapify (int[] array){
this.array = array;
}
public void heap (int[] aArray){
int left = 0;
int right = aArray.length - 1;
int n = aArray.length;
int numOfSwap = 0;
heapify1(aArray, left, right, numOfSwap );
}
public void heapify1 (int[] aArray, int left, int right, int numOfSwap) {
//from last one that have a child
for (int i = (right - 1)/2; i > left - 1; --i){
System.out.println("in heapify for loop with i = " + i + " number of swap: " + numOfSwap);
if (aArray[2*i + 2] > aArray[i]) {//if right child is bigger than parent
System.out.println("in heapify for loop and if #1: " + numOfSwap);
swap(aArray, i, 2*i + 2, right, numOfSwap);
}
else if (aArray[2*i + 1] > aArray[i]){
System.out.println("in heapify for loop and else if #2: " + numOfSwap);
swap(aArray, i, 2*i + 1, right, numOfSwap);
}
}
}
public int swap (int[] aArray, int parent, int child, int right, int numOfSwap ){
System.out.println("in swap before: " + numOfSwap );
int temp = aArray[parent];
aArray[parent] = aArray[child];
aArray[child] = temp;
numOfSwap = numOfSwap + 1;
System.out.println("inswap after: " + numOfSwap );
heapify1 (aArray, parent, right, numOfSwap );
return numOfSwap;
}
public static void main(String args[]) {
int[] array1 = new int[] {21,15,25,3,5,12,7,45,19,2,9};
Heapify hs = new Heapify(array1);
hs.heap(array1);
}
}
结果打印值为:
in heapify: 0
in heapify for loop with i = 4 number of swap: 0
in heapify for loop and if #1: 0
in swap before: 0
inswap after: 1
in heapify: 1
in heapify for loop with i = 4 number of swap: 1
in heapify for loop with i = 3 number of swap: 0
in heapify for loop and if #1: 0
in swap before: 0
inswap after: 1
in heapify: 1
in heapify for loop with i = 4 number of swap: 1
in heapify for loop with i = 3 number of swap: 1
in heapify for loop and else if #2: 1
in swap before: 1
inswap after: 2
in heapify: 2
in heapify for loop with i = 4 number of swap: 2
in heapify for loop with i = 3 number of swap: 2
in heapify for loop with i = 2 number of swap: 0
in heapify for loop with i = 1 number of swap: 0
in heapify for loop and else if #2: 0
我不明白为什么
swap
将numOfSwap = 1
传递给heapify1
,但是在for循环中,第二次迭代时,numOfSwap
被值0覆盖。同样在后一种情况下,为什么这样的行为覆盖发生在第三次迭代?我知道这可能是“按引用传递”或“按值传递”的问题,但真正令我困惑的一件事是numOfSwap在交换中已从0更新为1,交换再次调用heapify1成功将numOfSwap = 1传递给heapify1。但是,为什么迭代后numOfSwap在for循环中被初始化?
最佳答案
heapify1
方法有两种不同的上下文。
一种是在heapify1(aArray, left, right, numOfSwap );
方法中调用heap
时。在这种情况下,numOfSwap
为0,并保持为0。在这种情况下,执行for
循环。它可能看起来像“ numOfSwap在迭代后在for循环中被初始化了吗?”,但这不是事实。该值从不修改,并保持0。
另一个上下文是在heapify1 (aArray, parent, right, numOfSwap );
方法中调用swap
时,因此可以说“ swap再次调用heapify1,将numOfSwap = 1成功传递给heapify1”。但是这些传递的值仅在此上下文中使用,并且与提到的第一个上下文无关,并且不会修改numOfSwap
的值为0。