А Min-Heap це повне бінарне дерево, в якому значення в кожному внутрішньому вузлі менше або дорівнює значенням у дочірніх вузлах.
Відображення елементів купи в масив є тривіальним: якщо вузол зберігається за індексом k , тоді його ліва дитина зберігається за індексом 2k+1 і його права дитина за індексом 2k+2 для Індексація на основі 0 і для 1 індексація на основі ліва дитина буде на 2 тис і права дитина буде на 2k+1 .
Приклад мінімальної купи:
5 13 / / 10 15 16 31 / / / 30 41 51 100 41>
Як представлена мінімальна купа?
Мінімальна купа — це повне бінарне дерево. Мінімальна купа зазвичай представляється у вигляді масиву. Кореневий елемент буде at Прибуток[0] . Для будь-якого i-го вузла, тобто Arr[i] :
- Arr[(i -1) / 2] повертає батьківський вузол. Arr[(2 * i) + 1] повертає лівий дочірній вузол. Arr[(2 * i) + 2] повертає правий дочірній вузол.
Операції з мінімальною купою:
- getMin() : повертає кореневий елемент Min Heap. Час Складність цієї операції становить О(1) . extractMin() : видаляє мінімальний елемент із MinHeap. Часова складність цієї операції становить O(Log n) оскільки ця операція потребує підтримки властивості heap (за допомогою виклику heapify()) після видалення root. insert() : вставлення нового ключа займає O(Log n) час. Додаємо новий ключ у кінці дерева. Якщо новий ключ більший за батьківський, нам не потрібно нічого робити. В іншому випадку нам потрібно перейти вгору, щоб виправити порушену властивість купи.
Нижче наведено реалізацію Min Heap у Python –
веб-сервіси Java
Python3
# Python3 implementation of Min Heap> > import> sys> > class> MinHeap:> > > def> __init__(> self> , maxsize):> > self> .maxsize> => maxsize> > self> .size> => 0> > self> .Heap> => [> 0> ]> *> (> self> .maxsize> +> 1> )> > self> .Heap[> 0> ]> => -> 1> *> sys.maxsize> > self> .FRONT> => 1> > > # Function to return the position of> > # parent for the node currently> > # at pos> > def> parent(> self> , pos):> > return> pos> /> /> 2> > > # Function to return the position of> > # the left child for the node currently> > # at pos> > def> leftChild(> self> , pos):> > return> 2> *> pos> > > # Function to return the position of> > # the right child for the node currently> > # at pos> > def> rightChild(> self> , pos):> > return> (> 2> *> pos)> +> 1> > > # Function that returns true if the passed> > # node is a leaf node> > def> isLeaf(> self> , pos):> > return> pos> *> 2> >> self> .size> > > # Function to swap two nodes of the heap> > def> swap(> self> , fpos, spos):> > self> .Heap[fpos],> self> .Heap[spos]> => self> .Heap[spos],> self> .Heap[fpos]> > > # Function to heapify the node at pos> > def> minHeapify(> self> , pos):> > > # If the node is a non-leaf node and greater> > # than any of its child> > if> not> self> .isLeaf(pos):> > if> (> self> .Heap[pos]>> self> .Heap[> self> .leftChild(pos)]> or> > self> .Heap[pos]>> self> .Heap[> self> .rightChild(pos)]):> > > # Swap with the left child and heapify> > # the left child> > if> self> .Heap[> self> .leftChild(pos)] <> self> .Heap[> self> .rightChild(pos)]:> > self> .swap(pos,> self> .leftChild(pos))> > self> .minHeapify(> self> .leftChild(pos))> > > # Swap with the right child and heapify> > # the right child> > else> :> > self> .swap(pos,> self> .rightChild(pos))> > self> .minHeapify(> self> .rightChild(pos))> > > # Function to insert a node into the heap> > def> insert(> self> , element):> > if> self> .size>> => self> .maxsize :> > return> > self> .size> +> => 1> > self> .Heap[> self> .size]> => element> > > current> => self> .size> > > while> self> .Heap[current] <> self> .Heap[> self> .parent(current)]:> > self> .swap(current,> self> .parent(current))> > current> => self> .parent(current)> > > # Function to print the contents of the heap> > def> Print> (> self> ):> > for> i> in> range> (> 1> , (> self> .size> /> /> 2> )> +> 1> ):> > print> (> ' PARENT : '> +> str> (> self> .Heap[i])> +> ' LEFT CHILD : '> +> > str> (> self> .Heap[> 2> *> i])> +> ' RIGHT CHILD : '> +> > str> (> self> .Heap[> 2> *> i> +> 1> ]))> > > # Function to build the min heap using> > # the minHeapify function> > def> minHeap(> self> ):> > > for> pos> in> range> (> self> .size> /> /> 2> ,> 0> ,> -> 1> ):> > self> .minHeapify(pos)> > > # Function to remove and return the minimum> > # element from the heap> > def> remove(> self> ):> > > popped> => self> .Heap[> self> .FRONT]> > self> .Heap[> self> .FRONT]> => self> .Heap[> self> .size]> > self> .size> -> => 1> > self> .minHeapify(> self> .FRONT)> > return> popped> > # Driver Code> if> __name__> => => '__main__'> :> > > print> (> 'The minHeap is '> )> > minHeap> => MinHeap(> 15> )> > minHeap.insert(> 5> )> > minHeap.insert(> 3> )> > minHeap.insert(> 17> )> > minHeap.insert(> 10> )> > minHeap.insert(> 84> )> > minHeap.insert(> 19> )> > minHeap.insert(> 6> )> > minHeap.insert(> 22> )> > minHeap.insert(> 9> )> > minHeap.minHeap()> > > minHeap.> Print> ()> > print> (> 'The Min val is '> +> str> (minHeap.remove()))> |
>
порівняння рядків
>
Вихід:
The Min Heap is PARENT : 3 LEFT CHILD : 5 RIGHT CHILD :6 PARENT : 5 LEFT CHILD : 9 RIGHT CHILD :84 PARENT : 6 LEFT CHILD : 19 RIGHT CHILD :17 PARENT : 9 LEFT CHILD : 22 RIGHT CHILD :10 The Min val is 3>
Використання функцій бібліотеки:
Ми використовуємо heapq клас для реалізації Heaps у Python. За замовчуванням мінімальна купа реалізована цим класом.
Python3
upcasting
# Python3 program to demonstrate working of heapq> > from> heapq> import> heapify, heappush, heappop> > # Creating empty heap> heap> => []> heapify(heap)> > # Adding items to the heap using heappush function> heappush(heap,> 10> )> heappush(heap,> 30> )> heappush(heap,> 20> )> heappush(heap,> 400> )> > # printing the value of minimum element> print> (> 'Head value of heap : '> +> str> (heap[> 0> ]))> > # printing the elements of the heap> print> (> 'The heap elements : '> )> for> i> in> heap:> > print> (i, end> => ' '> )> print> (> '
'> )> > element> => heappop(heap)> > # printing the elements of the heap> print> (> 'The heap elements : '> )> for> i> in> heap:> > print> (i, end> => ' '> )> |
>
тестові випадки junit
>
Вихід:
Head value of heap : 10 The heap elements : 10 30 20 400 The heap elements : 20 30 400>