logo

Introduzione a Max-Heap: tutorial sulla struttura dei dati e sugli algoritmi

UN Max-Heap è definito come un tipo di La struttura dati heap è un tipo di albero binario comunemente utilizzato in informatica per vari scopi, tra cui l'ordinamento, la ricerca e l'organizzazione dei dati.

Introduzione alla struttura dei dati Max-Heap



Scopo e casi d'uso di Max-Heap:

Struttura dei dati Max-Heap in diverse lingue:

1. Heap massimo in C++

Un heap massimo può essere implementato utilizzando il metodo priorità_coda contenitore da Libreria di modelli standard (STL) . IL priorità_coda container è un tipo di adattatore container che fornisce un modo per archiviare elementi in una struttura dati simile a una coda in cui a ciascun elemento è associata una priorità.

  Synt  ax: priority_queuemaxH;>

2. Max Heap in Java

In Java, è possibile implementare un heap massimo utilizzando il metodo PriorityQueue classe da pacchetto java.util . La classe PriorityQueue è una coda di priorità che fornisce un modo per archiviare elementi in una struttura dati simile a una coda in cui a ciascun elemento è associata una priorità.



  Syntax  : PriorityQueue maxHeap= new PriorityQueue(Comparator.reverseOrder());>

3. Max-Heap in Python

In Python, un heap massimo può essere implementato utilizzando il metodo heapq modulo, che fornisce funzioni per l'implementazione degli heap. Nello specifico, il modulo heapq fornisce un modo per creare e manipolare strutture di dati heap.

  Synt  ax: heap = []  heapify(heap)>

4. Max-Heap in C#

In C#, è possibile implementare un heap massimo utilizzando la classe PriorityQueue da Spazio dei nomi System.Collections.Generic . La classe PriorityQueue è una coda di priorità che fornisce un modo per archiviare elementi in una struttura dati simile a una coda in cui a ciascun elemento è associata una priorità.

  Syntax:   var maxHeap = new PriorityQueue((a, b) =>b-a);>

5. Heap massimo in JavaScript

Un heap massimo è un albero binario in cui ogni nodo ha un valore maggiore o uguale ai suoi figli. In JavaScript, puoi implementare un heap massimo utilizzando un array, in cui il primo elemento rappresenta il nodo radice e i figli di un nodo all'indice io si trovano negli indici 2i+1 E 2i+2.



Syntax: const miaxHeap = new MaxHeap();>

Differenza tra Heap massimo e minimo

Mucchio minimo Mucchio massimo
1. In un Min-Heap la chiave presente nel nodo radice deve essere inferiore o uguale a tra le chiavi presenti in tutti i suoi figli. In un Max-Heap la chiave presente nel nodo radice deve essere maggiore o uguale tra le chiavi presenti in tutti i suoi figli.
2. In un Min-Heap l'elemento chiave minimo presente alla radice. In un Max-Heap l'elemento chiave massimo presente alla radice.
3. Un Min-Heap utilizza la priorità crescente. Un Max-Heap utilizza la priorità decrescente.
4. Nella costruzione di un Min-Heap, l'elemento più piccolo ha la priorità. Nella costruzione di un Max-Heap, l'elemento più grande ha la priorità.
5. In un Min-Heap, l'elemento più piccolo è il primo ad essere estratto dall'heap. In un Max-Heap, l'elemento più grande è il primo ad essere estratto dall'heap.

Implementazione interna della struttura dati Max-Heap:

UN L'heap minimo è in genere rappresentato come un array .

  • L'elemento radice sarà a Arrivo[0] .
  • Per ogni i-esimo nodo Arr[i].
    • il figlio sinistro è memorizzato in index 2i+1
    • Il figlio destro è archiviato in index 2i+2
    • Il genitore è archiviato al piano indice ((i-1)/2)

L'implementazione interna del Max-Heap richiede 3 passaggi principali:

  1. Inserimento : Per inserire un nuovo elemento nell'heap, viene aggiunto alla fine dell'array e quindi fatto bollire finché non soddisfa la proprietà dell'heap.
  2. Cancellazione : Per eliminare l'elemento massimo (la radice dell'heap), l'ultimo elemento dell'array viene scambiato con la radice e la nuova radice viene ridotta finché non soddisfa la proprietà dell'heap.
  3. Heapify : è possibile utilizzare un'operazione di heapify per creare un heap massimo da un array non ordinato.

Operazioni sulla struttura dati Max-heap e loro implementazione:

Ecco alcune operazioni comuni che possono essere eseguite su una struttura dati Heap Data Structure,

1. Inserimento nella struttura dati Max-Heap :

Gli elementi possono essere inseriti nell'heap seguendo un approccio simile a quello discusso sopra per l'eliminazione. L'idea è:

  • Per prima cosa aumenta la dimensione dell'heap di 1, in modo che possa memorizzare il nuovo elemento.
  • Inserisci il nuovo elemento alla fine dell'heap.
  • Questo elemento appena inserito potrebbe distorcere le proprietà di Heap per i suoi genitori. Quindi, per mantenere le proprietà di Heap, heapifica questo elemento appena inserito seguendo un approccio dal basso verso l'alto.

Illustrazione:

Supponiamo che l'Heap sia un Max-Heap come:

Inserimento nell'heap massimo

Inserimento nell'heap massimo

Implementazione dell'operazione di inserimento in Max-Heap:

C++




programma di array bidimensionale in c

// C++ program to insert new element to Heap> #include> using> namespace> std;> #define MAX 1000 // Max size of Heap> // Function to heapify ith node in a Heap> // of size n following a Bottom-up approach> void> heapify(>int> arr[],>int> n,>int> i)> {> >// Find parent> >int> parent = (i - 1) / 2;> >if> (arr[parent]>0) {> >// For Max-Heap> >// If current node is greater than its parent> >// Swap both of them and call heapify again> >// for the parent> >if> (arr[i]>arr[genitore]) {> >swap(arr[i], arr[parent]);> >// Recursively heapify the parent node> >heapify(arr, n, parent);> >}> >}> }> // Function to insert a new node to the Heap> void> insertNode(>int> arr[],>int>& n,>int> Key)> {> >// Increase the size of Heap by 1> >n = n + 1;> >// Insert the element at end of Heap> >arr[n - 1] = Key;> >// Heapify the new node following a> >// Bottom-up approach> >heapify(arr, n, n - 1);> }> // A utility function to print array of size n> void> printArray(>int> arr[],>int> n)> {> >for> (>int> i = 0; i cout << arr[i] << ' '; cout << ' '; } // Driver Code int main() { // Array representation of Max-Heap // 10 // / // 5 3 // / // 2 4 int arr[MAX] = { 10, 5, 3, 2, 4 }; int n = 5; int key = 15; insertNode(arr, n, key); printArray(arr, n); // Final Heap will be: // 15 // / // 5 10 // / / // 2 4 3 return 0; }>

>

>

Giava




// Java program for implementing insertion in Heaps> public> class> insertionHeap {> >// Function to heapify ith node in a Heap> >// of size n following a Bottom-up approach> >static> void> heapify(>int>[] arr,>int> n,>int> i)> >{> >// Find parent> >int> parent = (i ->1>) />2>;> > >if> (arr[parent]>>0>) {> >// For Max-Heap> >// If current node is greater than its parent> >// Swap both of them and call heapify again> >// for the parent> >if> (arr[i]>arr[genitore]) {> > >// swap arr[i] and arr[parent]> >int> temp = arr[i];> >arr[i] = arr[parent];> >arr[parent] = temp;> > >// Recursively heapify the parent node> >heapify(arr, n, parent);> >}> >}> >}> >// Function to insert a new node to the heap.> >static> int> insertNode(>int>[] arr,>int> n,>int> Key)> >{> >// Increase the size of Heap by 1> >n = n +>1>;> > >// Insert the element at end of Heap> >arr[n ->1>] = Key;> > >// Heapify the new node following a> >// Bottom-up approach> >heapify(arr, n, n ->1>);> > >// return new size of Heap> >return> n;> >}> >/* A utility function to print array of size n */> >static> void> printArray(>int>[] arr,>int> n)> >{> >for> (>int> i =>0>; i System.out.println(arr[i] + ' '); System.out.println(); } // Driver Code public static void main(String args[]) { // Array representation of Max-Heap // 10 // / // 5 3 // / // 2 4 // maximum size of the array int MAX = 1000; int[] arr = new int[MAX]; // initializing some values arr[0] = 10; arr[1] = 5; arr[2] = 3; arr[3] = 2; arr[4] = 4; // Current size of the array int n = 5; // the element to be inserted int Key = 15; // The function inserts the new element to the heap and // returns the new size of the array n = insertNode(arr, n, Key); printArray(arr, n); // Final Heap will be: // 15 // / // 5 10 // / / // 2 4 3 } } // The code is contributed by Gautam goel>

>

>

C#




// C# program for implementing insertion in Heaps> using> System;> public> class> insertionHeap {> >// Function to heapify ith node in a Heap of size n following a Bottom-up approach> >static> void> heapify(>int>[] arr,>int> n,>int> i) {> >// Find parent> >int> parent = (i - 1) / 2;> >if> (arr[parent]>0) {> >// For Max-Heap> >// If current node is greater than its parent> >// Swap both of them and call heapify again> >// for the parent> >if> (arr[i]>arr[genitore]) {> >// swap arr[i] and arr[parent]> >int> temp = arr[i];> >arr[i] = arr[parent];> >arr[parent] = temp;> >// Recursively heapify the parent node> >heapify(arr, n, parent);> >}> >}> >}> >// Function to insert a new node to the heap.> >static> int> insertNode(>int>[] arr,>int> n,>int> Key) {> >// Increase the size of Heap by 1> >n = n + 1;> >// Insert the element at end of Heap> >arr[n - 1] = Key;> >// Heapify the new node following a> >// Bottom-up approach> >heapify(arr, n, n - 1);> >// return new size of Heap> >return> n;> >}> >/* A utility function to print array of size n */> >static> void> printArray(>int>[] arr,>int> n) {> >for> (>int> i = 0; i Console.WriteLine(arr[i] + ' '); Console.WriteLine(''); } public static void Main(string[] args) { // Array representation of Max-Heap // 10 // / // 5 3 // / // 2 4 // maximum size of the array int MAX = 1000; int[] arr = new int[MAX]; // initializing some values arr[0] = 10; arr[1] = 5; arr[2] = 3; arr[3] = 2; arr[4] = 4; // Current size of the array int n = 5; // the element to be inserted int Key = 15; // The function inserts the new element to the heap and // returns the new size of the array n = insertNode(arr, n, Key); printArray(arr, n); // Final Heap will be: // 15 // / // 5 10 // / / // 2 4 3 } } // This code is contributed by ajaymakvana.>

>

>

Javascript




// Javascript program for implement insertion in Heaps> // To heapify a subtree rooted with node i which is> // an index in arr[].Nn is size of heap> let MAX = 1000;> // Function to heapify ith node in a Heap of size n following a Bottom-up approach> function> heapify(arr, n, i)> {> >// Find parent> >let parent = Math.floor((i-1)/2);> >if> (arr[parent]>= 0) {> >// For Max-Heap> >// If current node is greater than its parent> >// Swap both of them and call heapify again> >// for the parent> >if> (arr[i]>arr[genitore]) {> >let temp = arr[i];> >arr[i] = arr[parent];> >arr[parent] = temp;> >// Recursively heapify the parent node> >heapify(arr, n, parent);> >}> >}> }> // Function to insert a new node to the Heap> function> insertNode(arr, n, Key)> {> >// Increase the size of Heap by 1> >n = n + 1;> >// Insert the element at end of Heap> >arr[n - 1] = Key;> >// Heapify the new node following a> >// Bottom-up approach> >heapify(arr, n, n - 1);> > >return> n;> }> /* A utility function to print array of size N */> function> printArray(arr, n)> {> >for> (let i = 0; i console.log(arr[i] + ' '); console.log(''); } let arr = [ 10, 5, 3, 2, 4 ]; let n = arr.length; let key = 15; n = insertNode(arr, n, key); printArray(arr, n); // This code is contributed by ajaymakvana>

>

>

Python3




# program to insert new element to Heap> # Function to heapify ith node in a Heap> # of size n following a Bottom-up approach> def> heapify(arr, n, i):> >parent>=> int>(((i>->1>)>/>2>))> ># For Max-Heap> ># If current node is greater than its parent> ># Swap both of them and call heapify again> ># for the parent> >if> arr[parent]>>0>:> >if> arr[i]>arr[genitore]:> >arr[i], arr[parent]>=> arr[parent], arr[i]> ># Recursively heapify the parent node> >heapify(arr, n, parent)> # Function to insert a new node to the Heap> def> insertNode(arr, key):> >global> n> ># Increase the size of Heap by 1> >n>+>=> 1> ># Insert the element at end of Heap> >arr.append(key)> ># Heapify the new node following a> ># Bottom-up approach> >heapify(arr, n, n>->1>)> # A utility function to print array of size n> def> printArr(arr, n):> >for> i>in> range>(n):> >print>(arr[i], end>=>' '>)> # Driver Code> # Array representation of Max-Heap> '''> >10> >/> >5 3> >/> >2 4> '''> arr>=> [>10>,>5>,>3>,>2>,>4>,>1>,>7>]> n>=> 7> key>=> 15> insertNode(arr, key)> printArr(arr, n)> # Final Heap will be:> '''> >15> >/> 5 10> / /> 2 4 3> Code is written by Rajat Kumar....> '''>

>

>

Produzione

15 5 10 2 4 3>

Complessità temporale: O(log(n)) ( dove n è il numero di elementi nell'heap )
Spazio ausiliario: SU)

2. Eliminazione nella struttura dei dati Max-Heap :

Eliminare un elemento in qualsiasi posizione intermedia nell'heap può essere costoso, quindi possiamo semplicemente sostituire l'elemento da eliminare con l'ultimo elemento ed eliminare l'ultimo elemento dell'heap.

  • Sostituisci la radice o l'elemento da eliminare con l'ultimo elemento.
  • Elimina l'ultimo elemento dall'heap.
  • Poiché l'ultimo elemento è ora posizionato nella posizione del nodo radice. Pertanto, potrebbe non seguire la proprietà heap. Pertanto, heapifica l'ultimo nodo posizionato nella posizione della radice.

Illustrazione :

Supponiamo che l'Heap sia un Max-Heap come:

Struttura dati Max-Heap

Struttura dati heap massima

L'elemento da eliminare è root, ovvero 10.

Processi :

L'ultimo elemento è 4.

Passo 1: Sostituisci l'ultimo elemento con root ed eliminalo.

Max-Heap-Data-Structure-step-1

Mucchio massimo

Passo 2 : Heapifica la radice.

Heap finale:

Max-Heap-Data-Structure-step-2

Mucchio massimo

Implementazione dell'operazione di eliminazione in Max-Heap:

C++




// C++ program for implement deletion in Heaps> #include> using> namespace> std;> // To heapify a subtree rooted with node i which is> // an index of arr[] and n is the size of heap> void> heapify(>int> arr[],>int> n,>int> i)> {> >int> largest = i;>// Initialize largest as root> >int> l = 2 * i + 1;>// left = 2*i + 1> >int> r = 2 * i + 2;>// right = 2*i + 2> >// If left child is larger than root> >if> (l arr[largest])> >largest = l;> >// If right child is larger than largest so far> >if> (r arr[largest])> >largest = r;> >// If largest is not root> >if> (largest != i) {> >swap(arr[i], arr[largest]);> >// Recursively heapify the affected sub-tree> >heapify(arr, n, largest);> >}> }> // Function to delete the root from Heap> void> deleteRoot(>int> arr[],>int>& n)> {> >// Get the last element> >int> lastElement = arr[n - 1];> >// Replace root with last element> >arr[0] = lastElement;> >// Decrease size of heap by 1> >n = n - 1;> >// heapify the root node> >heapify(arr, n, 0);> }> /* A utility function to print array of size n */> void> printArray(>int> arr[],>int> n)> {> >for> (>int> i = 0; i cout << arr[i] << ' '; cout << ' '; } // Driver Code int main() { // Array representation of Max-Heap // 10 // / // 5 3 // / // 2 4 int arr[] = { 10, 5, 3, 2, 4 }; int n = sizeof(arr) / sizeof(arr[0]); deleteRoot(arr, n); printArray(arr, n); return 0; }>

>

>

Giava




connettere il database java
// Java program for implement deletion in Heaps> public> class> deletionHeap {> >// To heapify a subtree rooted with node i which is> >// an index in arr[].Nn is size of heap> >static> void> heapify(>int> arr[],>int> n,>int> i)> >{> >int> largest = i;>// Initialize largest as root> >int> l =>2> * i +>1>;>// left = 2*i + 1> >int> r =>2> * i +>2>;>// right = 2*i + 2> >// If left child is larger than root> >if> (l arr[largest])> >largest = l;> >// If right child is larger than largest so far> >if> (r arr[largest])> >largest = r;> >// If largest is not root> >if> (largest != i) {> >int> swap = arr[i];> >arr[i] = arr[largest];> >arr[largest] = swap;> >// Recursively heapify the affected sub-tree> >heapify(arr, n, largest);> >}> >}> >// Function to delete the root from Heap> >static> int> deleteRoot(>int> arr[],>int> n)> >{> >// Get the last element> >int> lastElement = arr[n ->1>];> >// Replace root with first element> >arr[>0>] = lastElement;> >// Decrease size of heap by 1> >n = n ->1>;> >// heapify the root node> >heapify(arr, n,>0>);> >// return new size of Heap> >return> n;> >}> >/* A utility function to print array of size N */> >static> void> printArray(>int> arr[],>int> n)> >{> >for> (>int> i =>0>; i System.out.print(arr[i] + ' '); System.out.println(); } // Driver Code public static void main(String args[]) { // Array representation of Max-Heap // 10 // / // 5 3 // / // 2 4 int arr[] = { 10, 5, 3, 2, 4 }; int n = arr.length; n = deleteRoot(arr, n); printArray(arr, n); } }>

>

>

C#




// C# program for implement deletion in Heaps> using> System;> public> class> deletionHeap> {> >// To heapify a subtree rooted with node i which is> >// an index in arr[].Nn is size of heap> >static> void> heapify(>int> []arr,>int> n,>int> i)> >{> >int> largest = i;>// Initialize largest as root> >int> l = 2 * i + 1;>// left = 2*i + 1> >int> r = 2 * i + 2;>// right = 2*i + 2> >// If left child is larger than root> >if> (l arr[largest])> >largest = l;> >// If right child is larger than largest so far> >if> (r arr[largest])> >largest = r;> >// If largest is not root> >if> (largest != i)> >{> >int> swap = arr[i];> >arr[i] = arr[largest];> >arr[largest] = swap;> >// Recursively heapify the affected sub-tree> >heapify(arr, n, largest);> >}> >}> >// Function to delete the root from Heap> >static> int> deleteRoot(>int> []arr,>int> n)> >{> >// Get the last element> >int> lastElement = arr[n - 1];> >// Replace root with first element> >arr[0] = lastElement;> >// Decrease size of heap by 1> >n = n - 1;> >// heapify the root node> >heapify(arr, n, 0);> >// return new size of Heap> >return> n;> >}> >/* A utility function to print array of size N */> >static> void> printArray(>int> []arr,>int> n)> >{> >for> (>int> i = 0; i Console.Write(arr[i] + ' '); Console.WriteLine(); } // Driver Code public static void Main() { // Array representation of Max-Heap // 10 // / // 5 3 // / // 2 4 int []arr = { 10, 5, 3, 2, 4 }; int n = arr.Length; n = deleteRoot(arr, n); printArray(arr, n); } } // This code is contributed by Ryuga>

>

>

Javascript




> >// Javascript program for implement deletion in Heaps> > >// To heapify a subtree rooted with node i which is> >// an index in arr[].Nn is size of heap> >function> heapify(arr, n, i)> >{> >let largest = i;>// Initialize largest as root> >let l = 2 * i + 1;>// left = 2*i + 1> >let r = 2 * i + 2;>// right = 2*i + 2> >// If left child is larger than root> >if> (l arr[largest])> >largest = l;> >// If right child is larger than largest so far> >if> (r arr[largest])> >largest = r;> >// If largest is not root> >if> (largest != i)> >{> >let swap = arr[i];> >arr[i] = arr[largest];> >arr[largest] = swap;> >// Recursively heapify the affected sub-tree> >heapify(arr, n, largest);> >}> >}> >// Function to delete the root from Heap> >function> deleteRoot(arr, n)> >{> >// Get the last element> >let lastElement = arr[n - 1];> >// Replace root with first element> >arr[0] = lastElement;> >// Decrease size of heap by 1> >n = n - 1;> >// heapify the root node> >heapify(arr, n, 0);> >// return new size of Heap> >return> n;> >}> >/* A utility function to print array of size N */> >function> printArray(arr, n)> >{> >for> (let i = 0; i document.write(arr[i] + ' '); document.write(''); } let arr = [ 10, 5, 3, 2, 4 ]; let n = arr.length; n = deleteRoot(arr, n); printArray(arr, n); // This code is contributed by divyeshrabdiya07.>

>

>

Python3




# Python 3 program for implement deletion in Heaps> # To heapify a subtree rooted with node i which is> # an index of arr[] and n is the size of heap> def> heapify(arr, n, i):> >largest>=> i>#Initialize largest as root> >l>=> 2> *> i>+> 1> # left = 2*i + 1> >r>=> 2> *> i>+> 2> # right = 2*i + 2> >#If left child is larger than root> >if> (l and arr[l]>arr[più grande]): più grande = l #Se il figlio destro è più grande del più grande finora if (r e arr[r]> arr[più grande]): più grande = r # Se più grande non è root if (più grande!= i) : arr[i],arr[più grande]=arr[più grande],arr[i] #Heapifica ricorsivamente il sottoalbero interessato heapify(arr, n, più grande) #Funzione per eliminare la radice dall'Heap def deleteRoot(arr): global n # Ottieni l'ultimo elemento lastElement = arr[n - 1] # Sostituisci root con l'ultimo elemento arr[0] = lastElement # Diminuisce la dimensione dell'heap di 1 n = n - 1 # heapifica il nodo root heapify(arr, n, 0) # Una funzione di utilità per stampare un array di dimensione n def printArray(arr, n): for i in range(n): print(arr[i],end=' ') print() # Codice driver if __name__ == '__main__': # Rappresentazione array del Max-Heap # 10 # / # 5 3 # / # 2 4 arr = [ 10, 5, 3, 2, 4 ] n = len(arr) deleteRoot( arr) printArray(arr, n) # Questo codice è un contributo di Rajat Kumar.>

>

>

stringa nell'array c
Produzione

5 4 3 2>

Complessità temporale : O(log n) dove n è il numero di elementi nell'heap
Spazio ausiliario: SU)

3.Operazione Peek sulla struttura dati Max-heap:

Per accedere all'elemento massimo (ovvero la radice dell'heap), viene restituito il valore del nodo radice. La complessità temporale del peek in un heap massimo è O(1).

elemento di picco dell'heap massimo

Elemento di picco dell'heap massimo

Implementazione dell'operazione Peek in Max-Heap:

C++




#include> #include> int> main() {> >// Create a max heap with some elements using a priority_queue> >std::priority_queue<>int>>maxHeap;> >maxHeap.push(9);> >maxHeap.push(8);> >maxHeap.push(7);> >maxHeap.push(6);> >maxHeap.push(5);> >maxHeap.push(4);> >maxHeap.push(3);> >maxHeap.push(2);> >maxHeap.push(1);> >// Get the peak element (i.e., the largest element)> >int> peakElement = maxHeap.top();> >// Print the peak element> >std::cout <<>'Peak element: '> << peakElement << std::endl;> >return> 0;> }>

>

>

Giava




import> java.util.PriorityQueue;> public> class> GFG {> >public> static> void> main(String[] args) {> >// Create a max heap with some elements using a PriorityQueue> >PriorityQueue maxHeap =>new> PriorityQueue((a, b) ->b - a);> >maxHeap.add(>9>);> >maxHeap.add(>8>);> >maxHeap.add(>7>);> >maxHeap.add(>6>);> >maxHeap.add(>5>);> >maxHeap.add(>4>);> >maxHeap.add(>3>);> >maxHeap.add(>2>);> >maxHeap.add(>1>);> >// Get the peak element (i.e., the largest element)> >int> peakElement = maxHeap.peek();> >// Print the peak element> >System.out.println(>'Peak element: '> + peakElement);> >}> }>

>

>

C#




using> System;> using> System.Collections.Generic;> public> class> GFG {> >public> static> void> Main() {> >// Create a min heap with some elements using a PriorityQueue> >var> maxHeap =>new> PriorityQueue<>int>>();> >maxHeap.Enqueue(9);> >maxHeap.Enqueue(8);> >maxHeap.Enqueue(7);> >maxHeap.Enqueue(6);> >maxHeap.Enqueue(5);> >maxHeap.Enqueue(4);> >maxHeap.Enqueue(3);> >maxHeap.Enqueue(2);> >maxHeap.Enqueue(1);> >// Get the peak element (i.e., the smallest element)> >int> peakElement = maxHeap.Peek();> >// Print the peak element> >Console.WriteLine(>'Peak element: '> + peakElement);> >}> }> // Define a PriorityQueue class that uses a max heap> class> PriorityQueue>where> T : IComparable {> >private> List heap;> >public> PriorityQueue() {> >this>.heap =>new> List();> >}> >public> int> Count {> >get> {>return> this>.heap.Count; }> >}> >public> void> Enqueue(T item) {> >this>.heap.Add(item);> >this>.BubbleUp(>this>.heap.Count - 1);> >}> >public> T Dequeue() {> >T item =>this>.heap[0];> >int> lastIndex =>this>.heap.Count - 1;> >this>.heap[0] =>this>.heap[lastIndex];> >this>.heap.RemoveAt(lastIndex);> >this>.BubbleDown(0);> >return> item;> >}> >public> T Peek() {> >return> this>.heap[0];> >}> >private> void> BubbleUp(>int> index) {> >while> (index>0) {> >int> parentIndex = (index - 1) / 2;> >if> (>this>.heap[parentIndex].CompareTo(>this>.heap[index])>= 0) {> >break>;> >}> >Swap(parentIndex, index);> >index = parentIndex;> >}> >}> >private> void> BubbleDown(>int> index) {> >while> (index <>this>.heap.Count) {> >int> leftChildIndex = index * 2 + 1;> >int> rightChildIndex = index * 2 + 2;> >int> largestChildIndex = index;> >if> (leftChildIndex <>this>.heap.Count &&>this>.heap[leftChildIndex].CompareTo(>this>.heap[largestChildIndex])>0) {> >largestChildIndex = leftChildIndex;> >}> >if> (rightChildIndex <>this>.heap.Count &&>this>.heap[rightChildIndex].CompareTo(>this>.heap[largestChildIndex])>0) {> >largestChildIndex = rightChildIndex;> >}> >if> (largestChildIndex == index) {> >break>;> >}> >Swap(largestChildIndex, index);> >index = largestChildIndex;> >}> >}> >private> void> Swap(>int> i,>int> j) {> >T temp =>this>.heap[i];> >this>.heap[i] =>this>.heap[j];> >this>.heap[j] = temp;> >}> }>

>

>

Javascript




// Define a MaxHeap class that uses an array> class MaxHeap {> >constructor() {> >this>.heap = [];> >}> >push(item) {> >this>.heap.push(item);> >this>.bubbleUp(>this>.heap.length - 1);> >}> >pop() {> >let item =>this>.heap[0];> >let lastIndex =>this>.heap.length - 1;> >this>.heap[0] =>this>.heap[lastIndex];> >this>.heap.pop();> >this>.bubbleDown(0);> >return> item;> >}> >peak() {> >return> this>.heap[0];> >}> >bubbleUp(index) {> >while> (index>0) {> >let parentIndex = Math.floor((index - 1) / 2);> >if> (>this>.heap[parentIndex]>=>this>.heap[index]) {> >break>;> >}> >this>.swap(parentIndex, index);> >index = parentIndex;> >}> >}> >bubbleDown(index) {> >while> (index <>this>.heap.length) {> >let leftChildIndex = index * 2 + 1;> >let rightChildIndex = index * 2 + 2;> >let largestChildIndex = index;> >if> (leftChildIndex <>this>.heap.length &&>this>.heap[leftChildIndex]>>this>.heap[largestChildIndex]) {> >largestChildIndex = leftChildIndex;> >}> >if> (rightChildIndex <>this>.heap.length &&>this>.heap[rightChildIndex]>>this>.heap[largestChildIndex]) {> >largestChildIndex = rightChildIndex;> >}> >if> (largestChildIndex === index) {> >break>;> >}> >this>.swap(largestChildIndex, index);> >index = largestChildIndex;> >}> >}> >swap(i, j) {> >let temp =>this>.heap[i];> >this>.heap[i] =>this>.heap[j];> >this>.heap[j] = temp;> >}> }> // Create a max heap with some elements using an array> let maxHeap =>new> MaxHeap();> maxHeap.push(9);> maxHeap.push(8);> maxHeap.push(7);> maxHeap.push(6);> maxHeap.push(5);> maxHeap.push(4);> maxHeap.push(3);> maxHeap.push(2);> maxHeap.push(1);> // Get the peak element (i.e., the largest element)> let peakElement = maxHeap.peak();> // Print the peak element> console.log(>'Peak element: '> + peakElement);>

>

>

Python3




import> heapq> # Create a max heap with some elements using a list> max_heap>=> [>1>,>2>,>3>,>4>,>5>,>6>,>7>,>8>,>9>]> heapq.heapify(max_heap)> # Get the peak element (i.e., the largest element)> peak_element>=> heapq.nlargest(>1>, max_heap)[>0>]> # Print the peak element> print>(>'Peak element:'>, peak_element)>

>

>

Produzione

Peak element: 9>

Complessità temporale :

  • In un heap massimo implementato utilizzando un filevettoreo una lista, è possibile accedere all'elemento di picco in tempo costante, O(1), poiché si trova sempre alla radice dell'heap.
  • In un heap massimo implementato utilizzando aalbero binario, è possibile accedere all'elemento di picco anche in tempo O(1), poiché si trova sempre alla radice dell'albero.

Spazio ausiliario: SU)

4.Operazione heapify sulla struttura dati max-heap:

È possibile utilizzare un'operazione di heapify per creare un heap massimo da un array non ordinato. Questa operazione viene eseguita iniziando dall'ultimo nodo non foglia ed eseguendo ripetutamente l'operazione di bubble down finché tutti i nodi non soddisfano la proprietà heap. La complessità temporale dell'heapify in un heap massimo è O(n).

operazioni-heapify-in-max-heap

Operazioni di heapify in Max-Heap

5.Operazione di ricerca sulla struttura dati dell'heap massimo:

Per cercare un elemento nell'heap massimo, è possibile eseguire una ricerca lineare sull'array che rappresenta l'heap. Tuttavia, la complessità temporale di una ricerca lineare è O(n), il che non è efficiente. Pertanto, la ricerca non è un'operazione comunemente utilizzata in un heap massimo.

Ecco un esempio di codice che mostra come cercare un elemento in un heap massimo utilizzando std::trova() :

C++




#include> #include // for std::priority_queue> using> namespace> std;> int> main() {> >std::priority_queue<>int>>max_heap;> >// example max heap> > >max_heap.push(10);> >max_heap.push(9);> >max_heap.push(8);> >max_heap.push(6);> >max_heap.push(4);> >int> element = 6;>// element to search for> >bool> found =>false>;> >// Copy the max heap to a temporary queue and search for the element> >std::priority_queue<>int>>temp = max_heap;> >while> (!temp.empty()) {> >if> (temp.top() == element) {> >found =>true>;> >break>;> >}> >temp.pop();> >}> >if> (found) {> >std::cout <<>'Element found in the max heap.'> << std::endl;> >}>else> {> >std::cout <<>'Element not found in the max heap.'> << std::endl;> >}> >return> 0;> }>

>

>

Giava




import> java.util.PriorityQueue;> public> class> GFG {> >public> static> void> main(String[] args) {> >PriorityQueue maxHeap =>new> PriorityQueue((a, b) ->b - a);> >maxHeap.add(>3>);>// insert elements into the priority queue> >maxHeap.offer(>1>);> >maxHeap.offer(>4>);> >maxHeap.offer(>1>);> >maxHeap.offer(>6>);> >int> element =>6>;>// element to search for> >boolean> found =>false>;> >// Copy the max heap to a temporary queue and search for the element> >PriorityQueue temp =>new> PriorityQueue(maxHeap);> >while> (!temp.isEmpty()) {> >if> (temp.poll() == element) {> >found =>true>;> >break>;> >}> >}> >if> (found) {> >System.out.println(>'Element found in the max heap.'>);> >}>else> {> >System.out.println(>'Element not found in the max heap.'>);> >}> >}> }>

>

>

C#




using> System;> using> System.Collections.Generic;> class> Program {> >static> void> Main(>string>[] args) {> >// Create a max heap with some elements using a PriorityQueue> >PriorityQueue<>int>>maxHeap =>new> PriorityQueue<>int>>();> >maxHeap.Enqueue(10);> >maxHeap.Enqueue(9);> >maxHeap.Enqueue(8);> >maxHeap.Enqueue(6);> >maxHeap.Enqueue(4);> >int> element = 6;>// element to search for> >bool> found =>false>;> >// Copy the max heap to a temporary queue and search for the element> >PriorityQueue<>int>>temperatura =>new> PriorityQueue<>int>>(maxHeap);> >while> (temp.Count>0) {> >if> (temp.Peek() == element) {> >found =>true>;> >break>;> >}> >temp.Dequeue();> >}> >if> (found) {> >Console.WriteLine(>'Element found in the max heap.'>);> >}>else> {> >Console.WriteLine(>'Element not found in the max heap.'>);> >}> >}> }> // PriorityQueue class> class> PriorityQueue>where> T : IComparable {> >private> List heap =>new> List();> >public> void> Enqueue(T item) {> >heap.Add(item);> >int> child = heap.Count - 1;> >while> (child>0) {> >int> parent = (child - 1) / 2;> >if> (heap[child].CompareTo(heap[parent])>0) {> >T tmp = heap[child];> >heap[child] = heap[parent];> >heap[parent] = tmp;> >child = parent;> >}>else> {> >break>;> >}> >}> >}> >public> T Dequeue() {> >int> last = heap.Count - 1;> >T frontItem = heap[0];> >heap[0] = heap[last];> >heap.RemoveAt(last);> >last--;> >int> parent = 0;> >while> (>true>) {> >int> leftChild = parent * 2 + 1;> >if> (leftChild>Ultima) {> >break>;> >}> >int> rightChild = leftChild + 1;> >if> (rightChild <= last && heap[leftChild].CompareTo(heap[rightChild]) < 0) {> >leftChild = rightChild;> >}> >if> (heap[parent].CompareTo(heap[leftChild]) <0) {> >T tmp = heap[parent];> >heap[parent] = heap[leftChild];> >heap[leftChild] = tmp;> >parent = leftChild;> >}>else> {> >break>;> >}> >}> >return> frontItem;> >}> >public> T Peek() {> >return> heap[0];> >}> >public> int> Count {> >get> {> >return> heap.Count;> >}> >}> }>

>

>

Javascript




const maxHeap =>new> PriorityQueue((a, b) =>b - a);> maxHeap.add(3);>// insert elements into the priority queue> maxHeap.add(1);> maxHeap.add(4);> maxHeap.add(1);> maxHeap.add(6);> const element = 6;>// element to search for> let found =>false>;> // Copy the max heap to a temporary queue and search for the element> const temp =>new> PriorityQueue(maxHeap);> while> (!temp.isEmpty()) {> if> (temp.poll() === element) {> found =>true>;> break>;> }> }> if> (found) {> console.log(>'Element found in the max heap.'>);> }>else> {> console.log(>'Element not found in the max heap.'>);> }>

>

inserendo la stringa in Java

>

Python3




import> heapq> max_heap>=> [>10>,>8>,>7>,>6>,>5>,>3>,>2>,>1>]># example max heap> heapq._heapify_max(max_heap)> element>=> 6> # element to search for> found>=> False> # Copy the max heap to a temporary list and search for the element> temp>=> list>(max_heap)> while> temp:> >if> heapq._heappop_max(temp)>=>=> element:> >found>=> True> >break> if> found:> >print>(>'Element found in the max heap.'>)> else>:> >print>(>'Element not found in the max heap.'>)>

>

>

Produzione

Element found in the max heap.>

Complessità temporale : O(n), dove n è la dimensione dell'heap.
Spazio ausiliario : SU),

Applicazioni della struttura dati Max-Heap:

  • Algoritmo di heapsort: La struttura dei dati heap è la base per l'algoritmo heapsort, che è un algoritmo di ordinamento efficiente con una complessità temporale nel caso peggiore di O(n log n). L'algoritmo heapsort viene utilizzato in varie applicazioni, inclusa l'indicizzazione di database e l'analisi numerica.
  • Gestione della memoria: La struttura dei dati heap viene utilizzata nei sistemi di gestione della memoria per allocare e deallocare la memoria in modo dinamico. L'heap viene utilizzato per archiviare i blocchi di memoria e la struttura dei dati dell'heap viene utilizzata per gestire in modo efficiente i blocchi di memoria e allocarli ai programmi secondo necessità.
  • Algoritmi grafici: La struttura dei dati heap viene utilizzata in vari algoritmi grafici, inclusi l'algoritmo di Dijkstra, l'algoritmo di Prim e l'algoritmo di Kruskal. Questi algoritmi richiedono un'efficiente implementazione della coda di priorità, che può essere ottenuta utilizzando la struttura dei dati heap.
  • Pianificazione del lavoro: La struttura dei dati heap viene utilizzata negli algoritmi di pianificazione dei lavori, in cui le attività vengono pianificate in base alla priorità o alla scadenza. La struttura dei dati heap consente un accesso efficiente all'attività con la priorità più alta, rendendola una struttura dati utile per le applicazioni di pianificazione dei lavori.

Vantaggi della struttura dati Max-Heap:

  • Mantenere in modo efficiente il valore massimo: Un heap massimo consente l'accesso in tempo costante all'elemento massimo nell'heap, il che lo rende utile nelle applicazioni in cui è necessario trovare rapidamente l'elemento massimo.
  • Operazioni di inserimento ed eliminazione efficienti: Le operazioni di inserimento ed eliminazione in un heap massimo hanno una complessità temporale pari a O(log n), che le rende efficienti per grandi raccolte di elementi.
  • Code prioritarie: È possibile utilizzare un heap massimo per implementare una coda di priorità, utile in molte applicazioni come la pianificazione dei processi, la definizione delle priorità delle attività e la simulazione basata sugli eventi.
  • Ordinamento: È possibile utilizzare un heap massimo per implementare heapsort, che è un algoritmo di ordinamento efficiente che ha una complessità temporale nel caso peggiore di O(n log n).
  • Efficienza spaziale: Un heap massimo può essere implementato come un array, che richiede meno memoria rispetto ad altre strutture dati come un albero di ricerca binario o un elenco collegato.

La struttura dei dati dell'heap massimo è uno strumento utile ed efficiente per mantenere e manipolare raccolte di elementi, in particolare quando è necessario accedere rapidamente all'elemento massimo o quando è necessario ordinare o dare priorità agli elementi.