A munt màxim és un arbre binari complet en el qual el valor de cada node intern és major o igual que els valors dels fills d'aquest node. Mapejar els elements d'un munt en una matriu és trivial: si un node emmagatzema un índex k, el seu fill esquerre s'emmagatzema a l'índex 2k + 1 i el seu fill dret a l'índex 2k + 2.
Il·lustració: Munt màxim
Com es representa Max Heap?
A-Max Heap és un arbre binari complet. El munt A-Max normalment es representa com una matriu. L'element arrel estarà a Arr[0]. La taula següent mostra índexs d'altres nodes per a ith node, és a dir, Arr[i]:
Arr[(i-1)/2] Retorna el node pare.
Arr[(2*i)+1] Retorna el node fill esquerre.
Arr[(2*i)+2] Retorna el node fill dret.
Les operacions a Max Heap són les següents:
- getMax(): Retorna l'element arrel de Max Heap. La complexitat temporal d'aquesta operació és O(1) .
- extractMax(): Elimina l'element màxim de MaxHeap . La complexitat temporal d'aquesta operació és O (Registre n) ja que aquesta operació ha de mantenir la propietat heap trucant a la mètode heapify(). després de treure l'arrel.
- inserir(): S'ha d'inserir una nova clau O (Registre n) temps. Afegim una nova clau al final de l'arbre. Si la nova clau és més petita que la seva pare, no hem de fer res. En cas contrari, haurem de recórrer cap amunt per arreglar la propietat del munt violada.
Nota: A la implementació següent, fem una indexació des de l'índex 1 per simplificar la implementació.
Mètodes:
Hi ha 2 mètodes pels quals podem assolir l'objectiu que s'indica:
- Enfocament bàsic mitjançant la creació maxHeapify() mètode
- Utilitzant Collections.reverseOrder() mètode mitjançant Funcions de biblioteca
Mètode 1: Enfocament bàsic mitjançant la creació maxHeapify() mètode
Crearem un mètode assumint que els subarbres esquerre i dret ja estan amuntegats, només necessitem arreglar l'arrel.
Exemple
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>(mida /> 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)]>Munt[rightChild (pos)]) { intercanvi (pos, leftChild (pos)); maxHeapify(leftChild(pos)); } else { swap(pos, rightChild(pos)); maxHeapify(rightChild(pos)); } } } // Mètode 7 // Insereix un element nou per al munt màxim public void insert(int element) { Heap[size] = element; // Travessa cap amunt i corregeix la propietat violada int current = size; mentre que (Heap[actual]> Heap[parent(current)]) { swap(current, parent(current)); actual = pare(actual); } mida++; } // Mètode 8 // Per mostrar l'heap public void print() { for (int i = 0; i 2; i++) { System.out.print('Parent Node: ' + Heap[i]); if (leftChild(i) // si el fill està fora del límit // de la matriu System.out.print(' Left Child Node: ' + Heap[leftChild(i)]); if (rightChild(i) ) // l'índex secundari correcte // no ha d'estar fora de l'índex de la matriu System.out.print(' Right Child Node: ' + Heap[rightChild(i)]); ; // per a la nova línia } } // Mètode 9 // Elimina un element del munt màxim public int extractMax() { int popped = Heap[0] = Heap[--size]; ; return aparegut } // Mètode 10 // mètode del controlador principal public static void main(String[] arg) { // Mostra el missatge per a una millor lectura System.out.println('MaxHeap és '); = new MaxHeap(15); // Inserció de nodes maxHeap.insert(5); maxHeap.insert(10); maxHeap.insert(19); maxHeap.insert(22); maxHeap.insert(9); valor a la pila System.out.println('El valor màxim és ' + maxHeap.extractMax()); } }>>> |
>
// 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()); } }>
>>SortidaHead 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>