Java 大小根堆的实现

Heap是一种数据结构它是一个完全二叉树具有以下的特点:
image

  • Min-heap: 父节点的值小于或等于子节点的值;
  • Max-heap: 父节点的值大于或等于子节点的值;
public class minAndMaxheap {
    //大根堆和小根堆的实现
    //优先级队列默认是小根堆的实现
    static class MaxheapComparator implements Comparator<Integer> {
        @Override
        public int compare(Integer o1, Integer o2) {
            return o2-o1;
        }
    }

    public static void main(String[] args) {
        int[] arrForHeap = { 3, 5, 2, 7, 0, 1, 6, 4 };
        Queue<Integer> minHeap = new PriorityQueue<>();
        //大根堆实现
        Queue<Integer> maxHeap = new PriorityQueue<>(new MaxheapComparator());
        for (int i =0;i<arrForHeap.length;i++) {
            minHeap.add(arrForHeap[i]);
            maxHeap.add(arrForHeap[i]);
        }
        while (!minHeap.isEmpty()) {
            System.out.print(minHeap.poll()+" ");
        }
        System.out.println();
        while (!maxHeap.isEmpty()) {
            System.out.print(maxHeap.poll()+" ");
        }
    }
}
result:
0 1 2 3 4 5 6 7 
7 6 5 4 3 2 1 0 
Process finished with exit code 0
posted @ 2018-07-14 14:48  上帝爱吃苹果-Soochow  阅读(1795)  评论(0编辑  收藏  举报