UN Tas maximum est défini comme un type de La structure de données en tas est un type d'arbre binaire couramment utilisé en informatique à diverses fins, notamment le tri, la recherche et l'organisation des données.
Introduction à la structure de données Max-Heap
Objectif et cas d'utilisation de Max-Heap :
- File d'attente de priorité: L'une des principales utilisations de la structure de données de tas consiste à implémenter des files d'attente prioritaires.
- Tri en tas : La structure de données tas est également utilisée dans les algorithmes de tri.
- Gestion de la mémoire: La structure de données tas est également utilisée dans la gestion de la mémoire. Lorsqu'un programme doit allouer de la mémoire de manière dynamique, il utilise la structure de données du tas pour suivre la mémoire disponible.
- L'algorithme du plus court chemin de Dijkstra utilise une structure de données en tas pour garder une trace des sommets ayant le chemin le plus court depuis le sommet source.
Structure de données Max-Heap dans différentes langues :
1. Max-Heap en C++
Un tas maximum peut être implémenté en utilisant le File d'attente de priorité conteneur du Bibliothèque de modèles standard (STL) . Le File d'attente de priorité Le conteneur est un type d'adaptateur de conteneur qui permet de stocker des éléments dans une structure de données de type file d'attente dans laquelle chaque élément est associé à une priorité.
Synt ax: priority_queuemaxH;>2. Max-Heap en Java
En Java, un tas maximum peut être implémenté en utilisant le File d'attente de priorité classe de paquet java.util . La classe PriorityQueue est une file d'attente prioritaire qui permet de stocker des éléments dans une structure de données de type file d'attente dans laquelle chaque élément est associé à une priorité.
Syntax : PriorityQueue maxHeap= new PriorityQueue(Comparator.reverseOrder());>3. Max-Heap en Python
En Python, un tas maximum peut être implémenté en utilisant le tas module, qui fournit des fonctions pour implémenter des tas. Plus précisément, le module heapq fournit un moyen de créer et de manipuler des structures de données de tas.
Synt ax: heap = [] heapify(heap)>4. Max-Heap en C#
En C#, un tas maximum peut être implémenté à l'aide de la classe PriorityQueue du Espace de noms System.Collections.Generic . La classe PriorityQueue est une file d'attente prioritaire qui permet de stocker des éléments dans une structure de données de type file d'attente dans laquelle chaque élément est associé à une priorité.
Syntax: var maxHeap = new PriorityQueue((a, b) =>b-a);>5. Max-Heap en JavaScript
Un tas max est un arbre binaire dans lequel chaque nœud a une valeur supérieure ou égale à celle de ses enfants. En JavaScript, vous pouvez implémenter un tas maximum à l'aide d'un tableau, où le premier élément représente le nœud racine et les enfants d'un nœud à l'index. je sont situés aux indices 2i+1 et 2i+2.
Syntax: const miaxHeap = new MaxHeap();>Différence entre le tas Max et Min
Tas minimum Tas maximum 1. Dans un Min-Heap, la clé présente sur le nœud racine doit être inférieure ou égale à parmi les clés présentes sur tous ses enfants. Dans un Max-Heap, la clé présente sur le nœud racine doit être supérieure ou égale à parmi les clés présentes sur tous ses enfants. 2. Dans un Min-Heap, l'élément clé minimum présent à la racine. Dans un Max-Heap, l'élément clé maximum présent à la racine. 3. Un Min-Heap utilise la priorité croissante. Un Max-Heap utilise la priorité décroissante. 4. Dans la construction d’un Min-Heap, le plus petit élément est prioritaire. Dans la construction d’un Max-Heap, le plus gros élément est prioritaire. 5. Dans un Min-Heap, le plus petit élément est le premier à être extrait du tas. Dans un Max-Heap, le plus grand élément est le premier à être extrait du tas. Implémentation interne de la structure de données Max-Heap :
UN Le tas minimum est généralement représenté sous forme de tableau .
- L'élément racine sera à Arr[0] .
- Pour tout ième nœud Arr[i].
- l'enfant de gauche est stocké à l'index 2i+1
- L'enfant de droite est stocké à l'index 2i+2
- Le parent est stocké à l'étage d'indexation ((je-1)/2)
L'implémentation interne du Max-Heap nécessite 3 étapes majeures :
- Insertion : Pour insérer un nouvel élément dans le tas, il est ajouté à la fin du tableau puis bouillonné jusqu'à ce qu'il satisfasse à la propriété du tas.
- Effacement : Pour supprimer le maximum d'éléments (la racine du tas), le dernier élément du tableau est échangé avec la racine et la nouvelle racine est bouillonnée jusqu'à ce qu'elle satisfasse à la propriété du tas.
- Heapifier : Une opération heapify peut être utilisée pour créer un tas maximum à partir d'un tableau non trié.
Opérations sur la structure de données Max-heap et leur implémentation :
Voici quelques opérations courantes qui peuvent être effectuées sur une structure de données Heap Data Structure,
1. Insertion dans la structure de données Max-Heap :
Les éléments peuvent être insérés dans le tas en suivant une approche similaire à celle décrite ci-dessus pour la suppression. L'idée est de :
- Augmentez d’abord la taille du tas de 1, afin qu’il puisse stocker le nouvel élément.
- Insérez le nouvel élément à la fin du tas.
- Cet élément nouvellement inséré peut déformer les propriétés de Heap pour ses parents. Ainsi, afin de conserver les propriétés de Heap, empilez cet élément nouvellement inséré en suivant une approche ascendante.
Illustration:
Supposons que le tas soit un tas maximum comme :
Insertion dans le tas Max
Implémentation de l'opération d'insertion dans Max-Heap :
C++
3D en autocad
// 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[parent]) {>>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; }>>>Java
// 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[parent]) {>>>// 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[parent]) {>>// 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[parent]) {>>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[parent]:>>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....>'''>>>Sortir15 5 10 2 4 3>Complexité temporelle : O(log(n)) ( où n est le nombre d'éléments dans le tas )
Espace auxiliaire : Sur)2. Suppression dans la structure de données Max-Heap :
Supprimer un élément à n'importe quelle position intermédiaire du tas peut être coûteux, nous pouvons donc simplement remplacer l'élément à supprimer par le dernier élément et supprimer le dernier élément du tas.
- Remplacez la racine ou l'élément à supprimer par le dernier élément.
- Supprimez le dernier élément du tas.
- Puisque le dernier élément est désormais placé à la position du nœud racine. Il se peut donc qu’il ne suive pas la propriété du tas. Par conséquent, empilez le dernier nœud placé à la position de la racine.
Illustration :
Supposons que le tas soit un tas maximum comme :
Structure de données de tas maximale
L'élément à supprimer est root, soit 10.
Processus :
Le dernier élément est 4.
Étape 1: Remplacez le dernier élément par root et supprimez-le.
Tas maximum
Étape 2 : Accumulez la racine.
Tas final :
Tas maximum
Implémentation de l'opération de suppression dans 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; }>>qu'est-ce que SVN Checkout>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[le plus grand]): le plus grand = l #Si l'enfant droit est plus grand que le plus grand jusqu'à présent if (r et arr[r]> arr[le plus grand]): le plus grand = r # Si le plus grand n'est pas la racine if (le plus grand != i) : arr[i],arr[largest]=arr[largest],arr[i] #Tasifier récursivement le sous-arbre affecté heapify(arr, n, plus grand) #Fonction pour supprimer la racine du tas def deleteRoot(arr): global n # Récupère le dernier élément lastElement = arr[n - 1] # Remplace la racine par le dernier élément arr[0] = lastElement # Diminue la taille du tas de 1 n = n - 1 # tasifie le nœud racine heapify(arr, n, 0) # Une fonction utilitaire pour imprimer un tableau de taille n def printArray(arr, n): for i in range(n): print(arr[i],end=' ') print() # Code du pilote si __name__ == '__main__' : # Représentation matricielle de Max-Heap # 10 # / # 5 3 # / # 2 4 arr = [ 10, 5, 3, 2, 4 ] n = len(arr) deleteRoot( arr) printArray(arr, n) # Ce code est fourni par Rajat Kumar.>>>Sortir5 4 3 2>Complexité temporelle : O(log n) où n est le nombre d'éléments dans le tas
Espace auxiliaire : Sur)3.Opération Peek sur la structure de données Max-heap :
Pour accéder à l'élément maximum (c'est-à-dire la racine du tas), la valeur du nœud racine est renvoyée. La complexité temporelle du coup d'oeil dans un tas maximum est O(1).
Élément de pointe du tas maximum
Implémentation de l'opération Peek dans 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;>}>>>Java
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
quel est le cas en SQL
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)>>>SortirPeak element: 9>Complexité temporelle :
- Dans un tas maximum implémenté à l'aide d'untableauou une liste, l'élément de pointe est accessible en temps constant, O(1), car il est toujours situé à la racine du tas.
- Dans un tas maximum implémenté à l'aide d'unarbre binaire, l'élément pic est également accessible en temps O(1), car il est toujours situé à la racine de l'arbre.
Espace auxiliaire : Sur)
4.Opération Heapify sur la structure de données Max-heap:
Une opération heapify peut être utilisée pour créer un tas maximum à partir d'un tableau non trié. Cela se fait en commençant par le dernier nœud non-feuille et en effectuant à plusieurs reprises l'opération de bulle vers le bas jusqu'à ce que tous les nœuds satisfassent à la propriété du tas. La complexité temporelle de heapify dans un tas maximum est O(n).
Opérations Heapify dans Max-Heap
5.Opération de recherche sur la structure de données Max-heap:
Pour rechercher un élément dans le tas max, une recherche linéaire peut être effectuée sur le tableau qui représente le tas. Cependant, la complexité temporelle d’une recherche linéaire est O(n), ce qui n’est pas efficace. Par conséquent, la recherche n’est pas une opération couramment utilisée dans un tas maximum.
Voici un exemple de code qui montre comment rechercher un élément dans un tas maximum en utilisant std :: trouver () :
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;>}>>>Java
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>>temp =>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>dernier) {>>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;>>}>>}>}>paire c++>>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.'>);>}>>>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.'>)>>>SortirElement found in the max heap.>Complexité temporelle : O(n), où n est la taille du tas.
Espace auxiliaire : Sur),Applications de la structure de données Max-Heap :
- Algorithme de tri en tas : La structure de données en tas constitue la base de l'algorithme de tri en tas, qui est un algorithme de tri efficace avec une complexité temporelle dans le pire des cas de O(n log n). L'algorithme de tri en tas est utilisé dans diverses applications, notamment l'indexation de bases de données et l'analyse numérique.
- Gestion de la mémoire: La structure de données tas est utilisée dans les systèmes de gestion de mémoire pour allouer et libérer de la mémoire de manière dynamique. Le tas est utilisé pour stocker les blocs de mémoire et la structure de données du tas est utilisée pour gérer efficacement les blocs de mémoire et les allouer aux programmes selon les besoins.
- Algorithmes graphiques : La structure de données en tas est utilisée dans divers algorithmes de graphes, notamment l'algorithme de Dijkstra, l'algorithme de Prim et l'algorithme de Kruskal. Ces algorithmes nécessitent une implémentation efficace de la file d’attente prioritaire, qui peut être obtenue en utilisant la structure de données en tas.
- Planification des travaux : La structure de données en tas est utilisée dans les algorithmes de planification des tâches, où les tâches sont planifiées en fonction de leur priorité ou de leur date limite. La structure de données en tas permet un accès efficace à la tâche la plus prioritaire, ce qui en fait une structure de données utile pour les applications de planification de tâches.
Avantages de la structure de données Max-Heap :
- Maintenir efficacement la valeur maximale : Un tas max permet un accès en temps constant au maximum d'éléments dans le tas, ce qui le rend utile dans les applications où l'élément maximum doit être trouvé rapidement.
- Opérations d'insertion et de suppression efficaces : Les opérations d'insertion et de suppression dans un tas maximum ont une complexité temporelle de O (log n), ce qui les rend efficaces pour les grandes collections d'éléments.
- Files d'attente prioritaires : Un tas maximum peut être utilisé pour implémenter une file d'attente prioritaire, ce qui est utile dans de nombreuses applications telles que la planification des tâches, la priorisation des tâches et la simulation basée sur les événements.
- Tri: Un tas maximum peut être utilisé pour implémenter le tri par tas, qui est un algorithme de tri efficace dont la complexité temporelle dans le pire des cas est de O (n log n).
- Efficacité spatiale : Un tas maximum peut être implémenté sous forme de tableau, ce qui nécessite moins de mémoire que d'autres structures de données telles qu'un arbre de recherche binaire ou une liste chaînée.
La structure de données Max Heap est un outil utile et efficace pour maintenir et manipuler des collections d'éléments, en particulier lorsque l'élément maximum doit être accédé rapidement ou lorsque les éléments doivent être triés ou hiérarchisés.




