天天看點

java堆大小_Java 大小根堆的實作

Heap是一種資料結構它是一個完全二叉樹具有以下的特點:

java堆大小_Java 大小根堆的實作

Min-heap: 父節點的值小于或等于子節點的值;

Max-heap: 父節點的值大于或等于子節點的值;

public class minAndMaxheap {

//大根堆和小根堆的實作

//優先級隊列預設是小根堆的實作

static class MaxheapComparator implements Comparator {

@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 minHeap = new PriorityQueue<>();

//大根堆實作

Queue maxHeap = new PriorityQueue<>(new MaxheapComparator());

for (int i =0;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

原文:https://www.cnblogs.com/keeya/p/9309617.html