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 {
/**
* @param A: Given an integer array
* @return: void
*/ public void heapify(int[] array) {
int heapSize = array.length;
for (int i = heapSize / - ; i >= ; i--) {
minHeapify(array, i, array.length);
}
} /// MaxHeapify is to build the max heap from the 'position'
public void minHeapify(int[] array, int position, int heapSize)
{
int left = left(position);
int right = right(position);
int minPosition = position; if (left < heapSize && array[left] < array[position]) {
minPosition = left;
} if (right < heapSize && array[right] < array[minPosition]) {
minPosition = right;
} if (position != minPosition) {
swap(position, minPosition, array);
minHeapify(array, minPosition, heapSize);
}
} public void swap(int i, int j, int[] A) {
int temp = A[i];
A[i] = A[j];
A[j] = temp;
} /// return the left child position
public int left(int i)
{
return * i + ;
}
/// return the right child position
public int right(int i)
{
return * i + ;
}
}