Вступ до Max-Heap – навчальні посібники зі структури даних і алгоритмів

А Макс-Хіп визначається як вид Структура даних купи — це тип двійкового дерева, який зазвичай використовується в інформатиці для різних цілей, включаючи сортування, пошук і впорядкування даних.

Вступ до структури даних Max-Heap

Призначення та випадки використання Max-Heap:

Структура даних Max-Heap на різних мовах:

1. Max-Heap в C++

Максимальна купа може бути реалізована за допомогою priority_queue контейнер від ст Стандартна бібліотека шаблонів (STL) . The priority_queue контейнер — це тип адаптера контейнера, який забезпечує спосіб зберігання елементів у структурі даних, подібній до черги, у якій кожен елемент має пов’язаний з ним пріоритет.

  Synt  ax: priority_queuemaxH; 

2. Max-Heap в Java

У Java максимальну купу можна реалізувати за допомогою PriorityQueue клас від пакет java.util . Клас PriorityQueue — це пріоритетна черга, яка забезпечує спосіб зберігання елементів у структурі даних, подібній до черги, у якій кожен елемент має пов’язаний з ним пріоритет.

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

3. Max-Heap в Python

У Python максимальну купу можна реалізувати за допомогою heapq модуль, який надає функції для реалізації куп. Зокрема, модуль heapq забезпечує спосіб створення та керування структурами даних купи.

  Synt  ax: heap = []  heapify(heap) 

4. Max-Heap в C#

У C# максимальну купу можна реалізувати за допомогою класу PriorityQueue з System.Collections.Generic простір імен . Клас PriorityQueue — це пріоритетна черга, яка забезпечує спосіб зберігання елементів у структурі даних, подібній до черги, у якій кожен елемент має пов’язаний з ним пріоритет.

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

5. Max-Heap у JavaScript

Максимальна купа — це бінарне дерево, у якому кожен вузол має значення, що перевищує або дорівнює його дочірнім вузлам. У JavaScript ви можете реалізувати максимальну купу за допомогою масиву, де перший елемент представляє кореневий вузол, а дочірні елементи вузла за індексом i розташовані за індексами 2і+1 і 2і+2.

Syntax: const miaxHeap = new MaxHeap(); 

Різниця між максимальною та мінімальною купою

Мінімальна купа Макс Хіп
1. У Min-Heap ключ, присутній у кореневому вузлі, має бути меншим або дорівнювати ключам, присутнім у всіх його дочірніх вузлах. У Max-Heap ключ, присутній у кореневому вузлі, повинен бути більшим або дорівнювати ключам, присутнім у всіх його дочірніх вузлах.
2. У Min-Heap мінімальний ключовий елемент, присутній у корені. У Max-Heap максимальний ключовий елемент, присутній у корені.
3. Min-Heap використовує зростаючий пріоритет. Max-Heap використовує низхідний пріоритет.
4. При побудові Min-Heap найменший елемент має пріоритет. При побудові Max-Heap найбільший елемент має пріоритет.
5. У Min-Heap найменший елемент є першим, який виривається з купи. У Max-Heap найбільший елемент є першим, який виривається з купи.

Внутрішня реалізація структури даних Max-Heap:

А Мінімальна купа зазвичай представляється у вигляді масиву .

  • Кореневий елемент буде at Прибуток[0] .
  • Для будь-якого i-го вузла Arr[i].
    • лівий дочірній елемент зберігається за індексом 2і+1
    • Правий дочірній елемент зберігається в індексі 2і+2
    • Батьківський елемент зберігається на рівні індексу ((i-1)/2)

Внутрішня реалізація Max-Heap вимагає 3 основних кроків:

  1. Вставка : щоб вставити новий елемент у купу, він додається в кінець масиву, а потім з’являється вгору, доки не задовольнить властивість купи.
  2. Видалення : Щоб видалити максимальний елемент (корінь купи), останній елемент у масиві міняється коренем, а новий корінь з’являється в спливаючому вигляді, доки він не задовольнить властивість купи.
  3. Heapify : операцію heapify можна використовувати для створення максимальної купи з несортованого масиву.

Операції над структурою даних максимальної купи та їх реалізація:

Ось деякі звичайні операції, які можна виконати над структурою даних Heap Data Structure,

1. Вставка в структуру даних Max-Heap :

Елементи можна вставляти в купу, дотримуючись подібного підходу, як описано вище для видалення. Ідея полягає в тому, щоб:

  • Спочатку збільште розмір купи на 1, щоб вона могла зберігати новий елемент.
  • Вставте новий елемент у кінець купи.
  • Цей нещодавно вставлений елемент може спотворити властивості Heap для своїх батьків. Отже, щоб зберегти властивості Heap, heapify цей щойно вставлений елемент за підходом знизу вгору.

Ілюстрація:

Припустимо, що купа є максимальною купою, як:

Вставка в максимальну купу

Вставка в максимальну купу

Реалізація операції вставки в Max-Heap:

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[батьківський]) {> > 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[батьківський]) {> > > // 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[батьківський]) {> > // 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[батьківський]) {> > 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[батьківський]:> > 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....> '''>

Вихід

15 5 10 2 4 3 

Часова складність: O(log(n)) ( де n – кількість елементів у купі )
Допоміжний простір: O(n)

2. Видалення в структурі даних Max-Heap :

Видалення елемента в будь-якій проміжній позиції в купі може бути дорогим, тому ми можемо просто замінити елемент, який потрібно видалити, останнім елементом і видалити останній елемент купи.

  • Замініть корінь або елемент, який потрібно видалити, на останній елемент.
  • Видалити останній елемент із купи.
  • Оскільки останній елемент тепер розміщено на позиції кореневого вузла. Отже, він може не відповідати властивості heap. Тому нагромаджуйте останній вузол, розміщений на місці кореня.

Ілюстрація :

Припустимо, що купа є максимальною купою, як:

Max-Heap-Data-Structure

Максимальна структура даних купи

Елемент, який потрібно видалити, це root, тобто 10.

процес :

Останній елемент - 4.

Крок 1: Замініть останній елемент на root і видаліть його.

Max-Heap-Data-Structure-step-1

Макс Хіп

Крок 2 : Heapify корінь.

Остаточна купа:

Max-Heap-Data-Structure-step-2

Макс Хіп

Реалізація операції видалення в 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; }>

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[найбільший]): найбільший = l #Якщо правий дочірній елемент більший за найбільший if (r і arr[r]> arr[найбільший]): найбільший = r # Якщо найбільший не є коренем if (найбільший != i) : arr[i],arr[largest]=arr[largest],arr[i] #Рекурсивне heapify ураженого піддерева heapify(arr, n, larger) #Функція для видалення кореня з Heap def deleteRoot(arr): global n # Отримати останній елемент lastElement = arr[n - 1] # Замінити корінь на останній елемент arr[0] = lastElement # Зменшити розмір купи на 1 n = n - 1 # heapify кореневий вузол heapify(arr, n, 0) # Допоміжна функція для друку масиву розміром n def printArray(arr, n): for i in range(n): print(arr[i],end=' ') print() # Код драйвера if __name__ == '__main__': # Представлення масиву Max-Heap # 10 # / # 5 3 # / # 2 4 arr = [ 10, 5, 3, 2, 4 ] n = len(arr) deleteRoot( arr) printArray(arr, n) # Цей код створено Раджатом Кумаром.>

Вихід

5 4 3 2 

Часова складність : O(log n), де n – кількість елементів у купі
Допоміжний простір: O(n)

3. Операція Peek у структурі даних Max-heap:

Щоб отримати доступ до максимального елемента (тобто кореня купи), повертається значення кореневого вузла. Часова складність перегляду в максимальній купі становить O(1).

peak-element-of-max-heap

Піковий елемент максимальної купи

Реалізація операції Peek у 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) ->б - а);> > 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)>

Вихід

Peak element: 9 

Часова складність :

  • У максимальній купі, реалізованій за допомогою an масив або список, піковий елемент може бути доступний у постійному часі, O(1), оскільки він завжди розташований у корені купи.
  • У максимальній купі, реалізованій за допомогою a бінарне дерево , піковий елемент також можна отримати за час O(1), оскільки він завжди розташований у корені дерева.

Допоміжний простір: O(n)

4. Операція Heapify у структурі даних Max-heap :

Операцію heapify можна використовувати для створення максимальної купи з несортованого масиву. Це робиться, починаючи з останнього вузла, що не є листом, і багаторазово виконуючи операцію «спускання», поки всі вузли не задовольнять властивість купи. Часова складність heapify у максимальній купі становить O(n).

heapify-operations-in-max-heap

Операції Heapify у Max-Heap

5. Операція пошуку в структурі даних Max-heap :

Щоб знайти елемент у максимальній купі, можна виконати лінійний пошук по масиву, який представляє купу. Однак часова складність лінійного пошуку становить O(n), що не є ефективним. Тому пошук не є широко використовуваною операцією в максимальній купі.

Ось приклад коду, який показує, як шукати елемент у максимальній купі за допомогою std::find() :

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) ->б - а);> > 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> >температура => 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>останній) {> > 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) =>б - а);> 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.'> )>

Вихід

Element found in the max heap. 

Часова складність : O(n), де n — розмір купи.
Допоміжний простір : O(n),

Застосування структури даних Max-Heap:

  • Алгоритм Heapsort: Структура даних купи є основою для алгоритму heapsort, який є ефективним алгоритмом сортування з найгіршою часовою складністю O(n log n). Алгоритм Heapsort використовується в різних програмах, включаючи індексацію бази даних і числовий аналіз.
  • Керування пам'яттю: Структура даних купи використовується в системах керування пам’яттю для динамічного розподілу та звільнення пам’яті. Купа використовується для зберігання блоків пам’яті, а структура даних купи використовується для ефективного керування блоками пам’яті та розподілу їх між програмами за потреби.
  • Алгоритми графів: Структура даних купи використовується в різних графових алгоритмах, включаючи алгоритм Дейкстри, алгоритм Прима та алгоритм Крускала. Ці алгоритми вимагають ефективної реалізації пріоритетної черги, що може бути досягнуто за допомогою структури даних купи.
  • Розклад роботи: Структура даних купи використовується в алгоритмах планування завдань, де завдання плануються на основі їх пріоритету або кінцевого терміну. Структура даних купи забезпечує ефективний доступ до завдання з найвищим пріоритетом, що робить її корисною структурою даних для програм планування завдань.

Переваги структури даних Max-Heap:

  • Ефективно підтримувати максимальне значення: Максимальна купа забезпечує постійний доступ до максимального елемента в купі, що робить його корисним у програмах, де максимальний елемент потрібно знайти швидко.
  • Ефективні операції вставки та видалення: Операції вставки та видалення в максимальній купі мають часову складність O(log n), що робить їх ефективними для великих колекцій елементів.
  • Пріоритетні черги: Максимальна купа може бути використана для реалізації черги пріоритетів, яка корисна в багатьох програмах, таких як планування завдань, пріоритезація завдань і симуляція, керована подіями.
  • Сортування: Максимальна купа може бути використана для реалізації heapsort, який є ефективним алгоритмом сортування, який має найгіршу часову складність O(n log n).
  • Ефективність простору: Максимальна купа може бути реалізована як масив, який потребує менше пам’яті порівняно з іншими структурами даних, такими як бінарне дерево пошуку або зв’язаний список.

Структура даних максимальної купи є корисним і ефективним інструментом для підтримки та маніпулювання колекціями елементів, особливо коли потрібно отримати швидкий доступ до максимального елемента або коли елементи потрібно відсортувати чи визначити пріоритети.