Java 检查最大顺序堆?
我知道,要使堆成为最大有序堆,父节点的键应该大于或等于子节点的键,最高键应该在根节点中。我只是想确定我的想法是否正确- 如果我想检查可比较对象的给定数组是否是最大有序堆Java 检查最大顺序堆?,java,heap,Java,Heap,我知道,要使堆成为最大有序堆,父节点的键应该大于或等于子节点的键,最高键应该在根节点中。我只是想确定我的想法是否正确- 如果我想检查可比较对象的给定数组是否是最大有序堆 boolean isItMaxOrdered(Comparable[] a) { //Check for 2 * i where i is the index of the first element //Check for 2 * i + 1 element where i is the index of th
boolean isItMaxOrdered(Comparable[] a) {
//Check for 2 * i where i is the index of the first element
//Check for 2 * i + 1 element where i is the index of the first element
//Compare if element i is greater than 2 * i and also if (2 * i) is greater than (2 * i + 1)th element
boolean check = false;
for(int i = 0; i < a.length; i++) {
if((2 * i + 1) < a.length)
if(a[i].compareTo(a[2 * i]) > 0 && a[i].compareTo(a[2 * i + 1]) > 0 && a[2 * i].compareTo(a[2 * i + 1]) > 0)
check = true;
else
check = false;
}
return check;
}
布尔isItMaxOrdered(可比[]a){
//检查2*i,其中i是第一个元素的索引
//检查2*i+1元素,其中i是第一个元素的索引
//比较元素i是否大于2*i,以及(2*i)是否大于第(2*i+1)个元素
布尔检查=假;
for(int i=0;i0&&a[i].compareTo(a[2*i+1])>0&&a[2*i].compareTo(a[2*i+1])>0)
检查=正确;
其他的
检查=错误;
}
退货检查;
}
但对于列表中包含的所有值,这不是一个应该为真的条件吗?我唯一能解释这一点的方法是对所有满足或不满足的值将check设置为true。实际上,我错了。您应该返回true代码>在最后。在循环中,检查条件是否为false,因为您可以立即返回false
。无需继续检查,因为一次错误排序意味着整个堆不是最大排序的。