How is this feature used?
I'm just studying a few lessons my lecturer gave me and I can't figure out how the function is used heapRebuild
! It doesn't change any globals, and it doesn't print anything, which doesn't return anything - is this how it should work? Shouldn't it be?
If you were told to use heapRebuild
to create a new function removeMac
, would you edit heapRebuild
?
public class MaxHeap<T extends Comparable<T>> implements Heap<T>{
private T[] heap;
private int lastIndex;
public T removeMax(){
T rootItem = heap[0];
heap[0] = heap[lastIndex-1];
lastIndex--;
heapRebuild(heap, 0, lastIndex);
return rootItem;
}
protected void heapRebuild(T[ ] items, int root, int size){
int child = 2*root+1;
if( child < size){
int rightChild = child+1;
if ((rightChild < size) &&
(items[rightChild].compareTo(items[child]) > 0)){
child = rightChild;
}
if (items[root].compareTo(items[child]) < 0){
T temp = items[root];
items[root] = items[child];
items[child] = temp;
heapRebuild(items, child, size);}
}
}
}
a source to share
Java is a count-by-value OO language. Methods can modify passed variable values.
Simplified example:
import java.util.Arrays;
public class Test {
public static void main(String... args) {
String[] strings = new String[] { "foo", "bar" };
System.out.println(Arrays.toString(strings)); // [foo, bar]
changeValue(strings);
System.out.println(Arrays.toString(strings)); // [foo, foo]
}
public static void changeValue(String[] strings) {
strings[1] = "foo";
}
}
a source to share
It modifies the array items
.
When you pass an object to a function in Java, it doesn't create a separate copy of the object.
So when your function heapRebuild
modifies the array items
, it modifies the original array that was passed to it.
Note that Java does not pass variable references, so if the function wrote items = whatever
, the caller's array will still refer to the old array instance.
a source to share