Min Heap in Python and its Operations

Min Heap in Python is a subclass of heaps. It’s the potential to categorize heaps into two classes: minimal and maximal heaps, respectively. A data structure referred to as a heap is known as a heap. Heaps, normally, are much like trees in that they’ve numerous nodes. In a heap, the final node is perhaps both empty or full. The parent node and the child node make up a heap. A binary heap is one other time period for a heap. Should you’re utilizing the max heap, the parent node is all times larger than or equal to the child node.

Additionally, it is essential to notice {that a} parent node is all the time lower than or equal to a child node within the min-heap.

Read Also: What is Python? A Beginner’s Guide

What does min heap in Python imply?

A min heap in python is a group of nodes. It is, without doubt, one of the heap varieties. There are two kinds of nodes in a min-heap. A heap comprises two nodes: a parent node, or root node, and a child node. A parent or root node’s worth ought to all the time be lower than or equal to the worth of the child node within the min-heap. When the parent node exceeds the child node, the heap turns into the max heap. Precedence is all the time given to the smallest aspect in a min-heap. It’s organized in ascending order.

As might be seen, not one of the parent nodes exceeds the child node. Thus, that is the best illustration of a min-heap. If this criterion just isn’t met, the heap is minimal.

Implementation of min heap utilizing library features in python

import heapq as heap
l=[ ]
heap.heappush(l,20)
heap.heappush(l,14)
heap.heappush(l,9)
heap.heappush(l,90)
heap.heappush(l,30)
heap.heappush(l,40)
print("The heap is:",l)
print("The parent node is:",heap.heappop(l))
print("The child nodes are:",l)

Clarification: Right here, we are going to generate a minimal pile utilizing the heap q library. Using all procedures to create a minimal heap. It should point out which node is the parent and which is the child. Moreover, it is going to present the heap’s minimal worth, figuring out which node is the parent or child.

Output
The heар is: [9, 20, 14, 90, 30, 40]
The parent node is: 9
The сhild nоdes аre: [14, 20, 40, 90, 30]

Representation of min heap in python

As is well known, the minimal heap is a binary tree, and an array is at all times an illustration of a min-heap. The basis aspect of the min-heap is array[0].

Parent node representation

array[(i -1) / 2] 

Left child node representation

array[(2 * i) + 1]

Right child node representation

array[(2 * i) + 1]

Which operations are accessible within the minimal heap?

  1. getMin()
  2. extractMin()
  3. insert()

getMin() operation:

  • It’s helpful to get the dad or mum node of the min heap.
  • The time соmрlexity оf getMin() is О(1) .

extractMin() operation:

  • The minimal ingredient from the min-heap is eliminated with this operation.
  • The time complexity of the extractMin() technique is O(log n).
  • After deleting the dad or mum node, extractMin() retains the heap property.

insert() operation:

  • This operation is useful for inserting a brand new node close to the heap’s finish.
  • If the brand new little one node is smaller than a dad or mum node, we should swap the dad or mum and little one nodes.
  • The time complexity so as to add a brand new node to the heap is O(log n).

Implementation of the min-heap with out using library features

import sys
class minheap:
    def __init__(self, size):
        self.storage=[0]*size
        self.size = size
        self.heap_size = 0
        self.Heap = [0]*(self.size + 1)
        self.Heap[0] = sys.maxsize * -1
        self.parent = 1
        self.root=1
    def getParentIndex(self,index):
        return (index-1)//2
    def getLeftChildIndex(self,index):
        return 2*index+1
    def getRightChildIndex(self,index):
        return 2*index+2
    def hasParent(self,index):
        return self.getParentIndex(index)>=0
    def insert(self,index):
        if self.heap_size >= self.size :
            return
        self.heap_size+= 1
        self.Heap[self.heap_size] = index
        heap = self.heap_size
        while self.Heap[heap] < self.Heap[heap//2]:
            self.swap(heap, heap//2)
            heap = heap//2
    def swap(self, left, right):
        self.Heap[left], self.Heap[right] = self.Heap[right], self.Heap[left]
    def root_node(self, i):
        if not (i >= (self.heap_size//2) and i <= self.heap_size):
            if (self.Heap[i] > self.Heap[2 * i]  or  self.Heap[i] > self.Heap[(2 * i) + 1]):
                if self.Heap[2 * i] < self.Heap[(2 * i) + 1]:
                    self.swap(i, 2 * i)
                    self.root_node(2 * i)
                else:
                    self.swap(i, (2 * i) + 1)
                    self.min_heapify((2 * i) + 1)
    def getMin(self):
        min_value = self.Heap[self.root]
        self.Heap[self.root] = self.Heap[self.root]
        self.size-= 1
        self.root_node(self.root)
        return min_value
    def extractMin(self):
        data=self.Heap[1]
        self.Heap[1]=self.Heap[self.size-1]
        self.size-=1
        return data
    def main(self):
       for i in range(1, (self.heap_size//2)+1):
            print("Parent Node:",str(self.Heap[i]),"Left Node:"+str(self.Heap[2 * i]),"Right Node:",str(self.Heap[2 * i + 1]))
minHeap = minheap(11)
minHeap.insert(70)
minHeap.insert(8)
minHeap.insert(80)
minHeap.insert(3)
minHeap.insert(90)
minHeap.insert(30)
minHeap.insert(23)
minHeap.insert(45)
minHeap.insert(100)
print("The Root element is " ,(minHeap.getMin()))
minHeap.main()
print("Remove node ", minHeap.extractMin())
minHeap.main()

Rationalization: We’re making a min heap in python utilizing and using all procedures to develop a minimal heap. It should point out which node is the mother or father and which is the kid. Moreover, it’s going to present the heap’s minimal worth, figuring out which node is the mother or father.

Output
The Root element is 3
Раrent Nоde: 3 Left Nоde:8 Right Nоde: 23
Раrent Nоde: 8 Left Nоde:45 Right Nоde: 90
Parent Node: 23 Left Node:80 Right Node: 30
Раrent Nоde: 45 Left Nоde:70 Right Nоde: 100
Remove node 3
Раrent Nоde: 100 Left Nоde:8 Right Nоde: 23
Раrent Nоde: 8 Left Nоde:45 Right Nоde: 90
Раrent Nоde: 23 Left Nоde:80 Right Nоde: 30
Раrent Nоde: 45 Left Nоde:70 Right Nоde: 100

Purposes of heap

  • Heap knowledge constructions are used for a k-way merging.
  • Graph algorithms like prim’s algorithm use heap knowledge construction.
  • Applicable for job scheduling algorithms.
  • That is advantageous for order statistics.

Conclusion

We have now lastly come to the tip of this article. We have now discovered lots in regard to the min-heap in Python, and we are going to proceed to be taught extra. A heap is a data structure which may be utilized in numerous conditions. I hope you have discovered this data informative and simple to grasp.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top