Build a min heap for a given a given array

public class Solution {
    public void heapify(int[] A) {
        // only heapify the parent nodes from 0 to A.length-1/2
        // from bottom to up, call minHeapify()
        for (int i=(A.length-1)/2; i>=0; i--) {
            minHeapify(i, A);
        }
    }
    
    public void minHeapify(int i, int[] A) {
        while (2*i+1 < A.length) {
            // A[son] is the minimum of the two children
            int son = 2*i+1;
            if (2*i+2<A.length && A[son] > A[2*i+2]) {
                son = 2*i+2;
            }
            if (A[son] >= A[i]) {
                break;
            }
            // swap the minimum with parent
            int temp = A[son];
            A[son] = A[i];
            A[i] = temp; 
            // check if son is a heap
            i = son;
        }
    }
}

發佈了187 篇原創文章 · 獲贊 0 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章