Given an integer array, heapify it into a min-heap array.
For a heap array A, A[0] is the root of heap, and for each A[i], A[i * 2 + 1] is the left child of A[i] and A[i * 2 + 2] is the right child of A[i].
基础题,一定要熟练掌握
public class Solution { public void heapify(int[] A) { for (int i = A.length / 2; i >= 0; i--) { heapify(A, i); } } private void heapify(int[] A, int i) { if (i > A.length) { return; } int left = i * 2 + 1 < A.length ? A[i*2+1] : Integer.MAX_VALUE; int right = i * 2 + 2 < A.length ? A[i*2+2] : Integer.MAX_VALUE; if (left < right && left < A[i]) { A[i*2+1] = A[i]; A[i] = left; heapify(A, i*2+1); } else if (right <= left && right < A[i]) { A[i*2+2] = A[i]; A[i] = right; heapify(A, i*2+2); } } }