我正在学习我的讲师给我的几门类(class),我不明白函数 heapRebuild
是如何使用的!它不会更改任何全局变量,也不会打印出任何内容,也不会返回任何内容——所以这应该有效吗?不应该,应该吗?
如果您被告知要使用 heapRebuild
来创建一个新函数 removeMac
,您会编辑 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);}
}
}
最佳答案
Java 是一种按值传递引用的 OO 语言。这些方法可以更改传入的可变值。
简化示例:
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";
}
}
关于java - 这个功能是如何使用的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2709945/