*[Lintcode] Heapify 堆化

来源:互联网 发布:护肤品真假查询软件 编辑:程序博客网 时间:2024/05/14 13:21

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[] A) {        for(int i = A.length / 2; i >= 0; i--)            heapify(A, i);    }        void heapify(int[] A, int last) {        int left = 2 * last + 1;        int right = 2* last + 2;        int small = last;        if(left < A.length && A[left] < A[small]) {            small = left;        }        if(right < A.length && A[right] < A[small]) {            small = right;        }        if(small != last) {            int tmp = A[small];            A[small] = A[last];            A[last] = tmp;            heapify(A, small);        }    }}


0 0