【发布时间】:2011-05-08 14:45:19
【问题描述】:
我正在尝试概述一种算法来确定我的数组是否是最小堆。是否有任何文件可以帮助我解决这个问题?我在 Apache 的网站上找到了它的一个函数,但它并没有准确地显示该函数是如何工作的;只是存在一个函数(BinaryHeap(boolean isMinHeap))。
【问题讨论】:
我正在尝试概述一种算法来确定我的数组是否是最小堆。是否有任何文件可以帮助我解决这个问题?我在 Apache 的网站上找到了它的一个函数,但它并没有准确地显示该函数是如何工作的;只是存在一个函数(BinaryHeap(boolean isMinHeap))。
【问题讨论】:
The Wikipedia article 应该可以帮到你。
这里有一些问题可以帮助您思考解决方案:
【讨论】:
我认为这会奏效!
bool checkminheap(int arr[],root)
{
if(root>=sizeof(arr)/sizeof(arr[0])-1)
return 1;
if(arr[root]>arr[2*root] || arr[root]>arr[2*root+1]) //check root is the smallest element
return 0;
if(!checkminheap(arr,2*root))//check leftsubtree
return 0;
if(!checkminheap(arr,2*root+1))//check rightsubtree
return 0;
return 1;
}
【讨论】:
添加一个带有java泛型支持的详细解决方案,它相对更容易遵循。
public static <T extends Comparable<T>> boolean isMinHeap(T arr[], int rootIndex) {
boolean isMaxH = true;
int lChild = 2 * rootIndex + 1;
int rChild = 2 * rootIndex + 2;
// Nothing to compare here, as lChild itself is larger then arr length.
if (lChild >= arr.length) {
return true;
}
if (arr[rootIndex].compareTo(arr[lChild]) > 0) {
return false;
} else {
isMaxH = isMaxH && isMinHeap(arr, lChild);
}
// rChild comparison not needed, return the current state of this root.
if (rChild >= arr.length) {
return isMaxH;
}
if (arr[rootIndex].compareTo(arr[rChild]) > 0) {
return false;
} else {
isMaxH = isMaxH && isMinHeap(arr, rChild);
}
return isMaxH;
}
【讨论】: