標籤:over empty sem ini 實現 integer 預設 int system
Heap是一種資料結構它是一個完全二叉樹具有以下的特點:
- 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
Java 大小根堆的實現