用Java写一个小程序判断一个数组是不是heap 10
3个回答
展开全部
挺简单的啊。。 关键在于理解heap
import java.util.Arrays;
public class Du {
public static void main(String[] args) {
int[] testAry1 = {1, 3, 5, 7, 9, 11};
System.out.println("{1, 3, 5, 7, 9, 11} is " + (isHeap(testAry1)? "": "NOT ") + "heap array.");
int[] testAry2 = {1, 3, 5, 7, 13, 9, 11};
System.out.println("{1, 3, 5, 7, 13, 9, 11} is " + (isHeap(testAry2)? "":"NOT ") + "heap array.");
}
/**
* Will receive an integer heap array, method will return true or false
* depending on whether the array is believed to be a valid heap or not
*
* @param heap
* 0-based integer array
* @return true if integer array is a heap, else false
*/
public static boolean isHeap(int[] heap) {
if(heap == null || heap.length == 0){
return false;
}
int[] ary = new int[heap.length];
for(int i = 0; i < heap.length; i++){
ary[i] = heap[i];
}
Arrays.sort(ary);
for(int i = 0; i < heap.length; i++){
if(ary[i] != heap[i]){
return false;
}
}
return true;
}
}
---------------
{1, 3, 5, 7, 9, 11} is heap array
{1, 3, 5, 7, 13, 9, 11} is NOT heap array
import java.util.Arrays;
public class Du {
public static void main(String[] args) {
int[] testAry1 = {1, 3, 5, 7, 9, 11};
System.out.println("{1, 3, 5, 7, 9, 11} is " + (isHeap(testAry1)? "": "NOT ") + "heap array.");
int[] testAry2 = {1, 3, 5, 7, 13, 9, 11};
System.out.println("{1, 3, 5, 7, 13, 9, 11} is " + (isHeap(testAry2)? "":"NOT ") + "heap array.");
}
/**
* Will receive an integer heap array, method will return true or false
* depending on whether the array is believed to be a valid heap or not
*
* @param heap
* 0-based integer array
* @return true if integer array is a heap, else false
*/
public static boolean isHeap(int[] heap) {
if(heap == null || heap.length == 0){
return false;
}
int[] ary = new int[heap.length];
for(int i = 0; i < heap.length; i++){
ary[i] = heap[i];
}
Arrays.sort(ary);
for(int i = 0; i < heap.length; i++){
if(ary[i] != heap[i]){
return false;
}
}
return true;
}
}
---------------
{1, 3, 5, 7, 9, 11} is heap array
{1, 3, 5, 7, 13, 9, 11} is NOT heap array
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询