A max-hromada je úplný binárny strom, v ktorom je hodnota v každom internom uzle väčšia alebo rovná hodnotám v potomkoch tohto uzla. Mapovanie prvkov haldy do poľa je triviálne: ak je uzol uložený ako index k, potom jeho ľavý potomok je uložený na indexe 2k + 1 a jeho pravý potomok na indexe 2k + 2.
Ilustrácia: Max Heap

Ako je zastúpený Max Heap?
A-Max Heap je kompletný binárny strom. Halda A-Max je zvyčajne reprezentovaná ako pole. Koreňový prvok bude na Arr[0]. Nižšie uvedená tabuľka ukazuje indexy ostatných uzlov pre i uzol, t.j. Arr[i]:
Arr[(i-1)/2] Vráti nadradený uzol.
Arr[(2*i)+1] Vráti ľavý podriadený uzol.
Arr[(2*i)+2] Vráti pravý podriadený uzol.
Operácie na Max Heap sú nasledovné:
- getMax(): Vracia koreňový prvok Max Heap. Časová zložitosť tejto operácie je O(1) .
- extraktMax(): Odstráni maximum prvku z MaxHeap . Časová zložitosť tejto operácie je O (Log n) pretože táto operácia potrebuje zachovať vlastnosť haldy volaním metóda heapify(). po odstránení koreňa.
- vložiť(): Vloženie nového kľúča trvá O (Log n) čas. Na koniec stromu pridáme nový kľúč. Ak je nový kľúč menší ako jeho rodič, nemusíme robiť nič. V opačnom prípade musíme prejsť nahor, aby sme opravili narušenú vlastnosť haldy.
Poznámka: V nižšie uvedenej implementácii robíme indexovanie od indexu 1, aby sme zjednodušili implementáciu.
Metódy:
Existujú 2 spôsoby, ktorými môžeme dosiahnuť uvedený cieľ:
java pole zoradené
- Základný prístup tvorením maxHeapify() metóda
- Použitím Collections.reverseOrder() metóda cez knižnicu Functions
Metóda 1: Základný prístup tvorením maxHeapify() metóda
Budeme vytvárať metódu za predpokladu, že ľavý a pravý podstrom je už nahromadený, potrebujeme len opraviť koreň.
Príklad
Java
// Java program to implement Max Heap> // Main class> public> class> MaxHeap {> >private> int>[] Heap;> >private> int> size;> >private> int> maxsize;> >// Constructor to initialize an> >// empty max heap with given maximum> >// capacity> >public> MaxHeap(>int> maxsize)> >{> >// This keyword refers to current instance itself> >this>.maxsize = maxsize;> >this>.size =>0>;> >Heap =>new> int>[>this>.maxsize];> >}> >// Method 1> >// Returning position of parent> >private> int> parent(>int> pos) {>return> (pos ->1>) />2>; }> >// Method 2> >// Returning left children> >private> int> leftChild(>int> pos) {>return> (>2> * pos) +>1>; }> >// Method 3> >// Returning right children> >private> int> rightChild(>int> pos)> >{> >return> (>2> * pos) +>2>;> >}> >// Method 4> >// Returning true if given node is leaf> >private> boolean> isLeaf(>int> pos)> >{> >if> (pos>(veľkosť />2>) && pos <= size) {> >return> true>;> >}> >return> false>;> >}> >// Method 5> >// Swapping nodes> >private> void> swap(>int> fpos,>int> spos)> >{> >int> tmp;> >tmp = Heap[fpos];> >Heap[fpos] = Heap[spos];> >Heap[spos] = tmp;> >}> >// Method 6> >// Recursive function to max heapify given subtree> >private> void> maxHeapify(>int> pos)> >{> >if> (isLeaf(pos))> >return>;> >if> (Heap[pos] || Heap[pos] if (Heap[leftChild(pos)]>Heap[rightChild(pos)]) { swap(pos, leftChild(pos)); maxHeapify(leftChild(pos)); } else { swap(pos, rightChild(pos)); maxHeapify(rightChild(pos)); } } } // Metóda 7 // Vloží nový prvok na maximálnu haldu public void insert(int element) { Heap[size] = element; // Prejdite nahor a opravte porušenú vlastnosť int current = size; while (Hroma[aktuálny]> Halda[rodič(aktuálny)]) { swap(aktuálny, rodič(aktuálny)); aktuálny = rodič(aktuálny); } veľkosť++; } // Metóda 8 // Zobrazenie haldy public void print() { for (int i = 0; i 2; i++) { System.out.print('Parent Node : ' + Heap[i]); if (leftChild(i) // ak je dieťa mimo hranice // poľa System.out.print(' Left Child Node: ' + Heap[leftChild(i)]); if (rightChild(i ) // pravý podradený index nesmie // byť mimo index poľa System.out.print(' Right Child Node: ' + Heap[rightChild(i)]); ; // pre nový riadok } } // Metóda 9 // Odstránenie prvku z max heap public int extractMax() { int popped = Heap[0] = Heap[--size]; ; návrat vyskočil } // Metóda 10 // metóda hlavného ovládača public static void main(String[] arg) { // Zobrazenie správy pre lepšiu čitateľnosť System.out.println('MaxHeap je '); = new MaxHeap(15) // Vlastné vstupy maxHeap.insert(3); maxHeap.insert(84); maxHeap.insert(6); maxHeap.insert(9); // volanie maxHeap.print(); hodnota v halde System.out.println('Maximálna hodnota je ' + maxHeap.extractMax()); } }> |
>
>Výkon
The Max Heap is Parent Node : 84 Left Child Node: 22 Right Child Node: 19 Parent Node : 22 Left Child Node: 17 Right Child Node: 10 Parent Node : 19 Left Child Node: 5 Right Child Node: 6 Parent Node : 17 Left Child Node: 3 Right Child Node: 9 The max val is 84>
Metóda 2: Použitie metódy Collections.reverseOrder() prostredníctvom funkcie knižnice
reťazec obsahuje java
Na implementáciu Heaps v Jave používame triedu PriorityQueue. Táto trieda štandardne implementuje Min Heap. Na implementáciu Max Heap používame metódu Collections.reverseOrder().
Príklad
Java
// Java program to demonstrate working> // of PriorityQueue as a Max Heap> // Using Collections.reverseOrder() method> // Importing all utility classes> import> java.util.*;> // Main class> class> GFG {> >// Main driver method> >public> static> void> main(String args[])> >{> >// Creating empty priority queue> >PriorityQueue pQueue> >=>new> PriorityQueue(> >Collections.reverseOrder());> >// Adding items to our priority queue> >// using add() method> >pQueue.add(>10>);> >pQueue.add(>30>);> >pQueue.add(>20>);> >pQueue.add(>400>);> >// Printing the most priority element> >System.out.println(>'Head value using peek function:'> >+ pQueue.peek());> >// Printing all elements> >System.out.println(>'The queue elements:'>);> >Iterator itr = pQueue.iterator();> >while> (itr.hasNext())> >System.out.println(itr.next());> >// Removing the top priority element (or head) and> >// printing the modified pQueue using poll()> >pQueue.poll();> >System.out.println(>'After removing an element '> >+>'with poll function:'>);> >Iterator itr2 = pQueue.iterator();> >while> (itr2.hasNext())> >System.out.println(itr2.next());> >// Removing 30 using remove() method> >pQueue.remove(>30>);> >System.out.println(>'after removing 30 with'> >+>' remove function:'>);> >Iterator itr3 = pQueue.iterator();> >while> (itr3.hasNext())> >System.out.println(itr3.next());> >// Check if an element is present using contains()> >boolean> b = pQueue.contains(>20>);> >System.out.println(>'Priority queue contains 20 '> >+>'or not?: '> + b);> >// Getting objects from the queue using toArray()> >// in an array and print the array> >Object[] arr = pQueue.toArray();> >System.out.println(>'Value in array: '>);> >for> (>int> i =>0>; i System.out.println('Value: ' + arr[i].toString()); } }> |
>
>Výkon
Head value using peek function:400 The queue elements: 400 30 20 10 After removing an element with poll function: 30 10 20 after removing 30 with remove function: 20 10 Priority queue contains 20 or not?: true Value in array: Value: 20 Value: 10>