码迷,mamicode.com
首页 > Windows程序 > 详细

lintcode-medium-Heapify

时间:2016-03-22 13:48:10      阅读:247      评论:0      收藏:0      [点我收藏+]

标签:

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].

 

 Given [3,2,1,4,5], return [1,2,3,4,5] or any legal heap array.

public class Solution {
    /**
     * @param A: Given an integer array
     * @return: void
     */
    public void heapify(int[] A) {
        // write your code here
        
        if(A == null || A.length == 0)
            return;
        
        for(int i = A.length / 2; i >= 0; i--){
            adjust(A, i);
        }
        
        return;
    }
    
    public void adjust(int[] A, int i){
        int left = i * 2 + 1;
        int right = i * 2 + 2;
        
        int min = i;
        
        if(left < A.length && A[left] < A[min])
            min = left;
        if(right < A.length && A[right] < A[min])
            min = right;
        
        if(i == min)
            return;
        
        swap(A, i, min);
        adjust(A, min);
        
        return;
    }
    
    public void swap(int[] A, int i, int j){
        int temp = A[i];
        A[i] = A[j];
        A[j] = temp;
        
        return;
    }
    
}

 

lintcode-medium-Heapify

标签:

原文地址:http://www.cnblogs.com/goblinengineer/p/5305993.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!