question:
Design a linear-time certification algorithm to check whether an array pq[] is a min-oriented heap.
answer:
import edu.princeton.cs.algs4.*; public class certification { public static boolean cer(int[] pq) { int N = pq.length - 1; for(int i = N/2; i >= 1; i--)//只要从一半开始往前,和堆排前半部分建堆原理一样 { if(2*i+1 <= N)//其实就是sink中的判断,但不用exch,然后我是用上一题的答案改的 { int j = 2*i; if(less(pq,j+1,j)) j++; if(less(pq,j,i)) return false; } else if(less(pq,2*i,i)) return false; } return true; } public static boolean less(int[] a, int i, int j) { return a[i] - a[j] < 0; } public static void main(String[] args) { int[] a = {0, 1, 2, 3, 4, 1, 6, 7}; StdOut.println(cer(a)); } }