logo CBCE Skill INDIA

Welcome to CBCE Skill INDIA. An ISO 9001:2015 Certified Autonomous Body | Best Quality Computer and Skills Training Provider Organization. Established Under Indian Trust Act 1882, Govt. of India. Identity No. - IV-190200628, and registered under NITI Aayog Govt. of India. Identity No. - WB/2023/0344555. Also registered under Ministry of Micro, Small & Medium Enterprises - MSME (Govt. of India). Registration Number - UDYAM-WB-06-0031863

What is a Heap Data Structure and how is it Implemented?


Heap Data Structure and how is it Implemented

A heap is a binary tree-based data structure that satisfies the heap property. A heap can be either a min-heap or a max-heap:

 

  1. Min-Heap: In a min-heap, the value of each parent node is less than or equal to the values of its children nodes. The root node contains the minimum value in the heap.

  2. Max-Heap: In a max-heap, the value of each parent node is greater than or equal to the values of its children nodes. The root node contains the maximum value in the heap.

Heap data structures are commonly used to implement priority queues and heap-sort algorithms due to their efficient insertion, deletion, and retrieval of the maximum or minimum element.

 

Here's how a heap is typically implemented:

  1. Array Representation: Heaps are often implemented using arrays. In a heap, the binary tree is stored in an array where each element corresponds to a node in the tree. The array is structured such that the children of the node at index i are stored at indices 2*i + 1 (left child) and 2*i + 2 (right child). Conversely, the parent of a node at index i is stored at index (i - 1) // 2.

  2. Insertion Operation: When inserting an element into a heap, it is added to the bottom level of the heap, maintaining the complete binary tree property. Then, the heap is adjusted by repeatedly comparing the new element with its parent node and swapping them if necessary to restore the heap property.

  3. Deletion Operation: When deleting an element from a heap, the root node (the maximum or minimum element) is removed. The last element in the heap is moved to the root position, and the heap is adjusted by repeatedly comparing the new root node with its children nodes and swapping them if necessary to restore the heap property.

  4. Heapify Operation: Heapify is an operation used to convert an array into a heap. It starts from the last non-leaf node and iterates upwards, ensuring that each subtree rooted at a node satisfies the heap property. This operation allows efficient construction of a heap from an unsorted array.

  5. Heap-sort Algorithm: Heap-sort is an efficient sorting algorithm based on the heap data structure. It involves building a max-heap from the input array, repeatedly removing the maximum element (root node) from the heap and placing it at the end of the array, and adjusting the heap after each removal. The resulting array is sorted in ascending order.

 

Here's a simple implementation of a min-heap in Python:

class MinHeap:
    def __init__(self):
        self.heap = []

    def insert(self, value):
        self.heap.append(value)
        self._heapify_up(len(self.heap) - 1)

    def extract_min(self):
        if not self.heap:
            return None
        min_value = self.heap[0]
        self.heap[0] = self.heap[-1]
        self.heap.pop()
        self._heapify_down(0)
        return min_value

    def _heapify_up(self, index):
        parent_index = (index - 1) // 2
        if parent_index >= 0 and self.heap[parent_index] > self.heap[index]:
            self.heap[parent_index], self.heap[index] = self.heap[index], self.heap[parent_index]
            self._heapify_up(parent_index)

    def _heapify_down(self, index):
        left_child_index = 2 * index + 1
        right_child_index = 2 * index + 2
        smallest = index
        if left_child_index < len(self.heap) and self.heap[left_child_index] < self.heap[smallest]:
            smallest = left_child_index
        if right_child_index < len(self.heap) and self.heap[right_child_index] < self.heap[smallest]:
            smallest = right_child_index
        if smallest != index:
            self.heap[index], self.heap[smallest] = self.heap[smallest], self.heap[index]
            self._heapify_down(smallest)

# Example usage:
heap = MinHeap()
heap.insert(5)
heap.insert(3)
heap.insert(8)
heap.insert(1)
heap.insert(6)

print("Extracted min:", heap.extract_min())  # Output: 1
print("Extracted min:", heap.extract_min())  # Output: 3

 

This example demonstrates a simple implementation of a min-heap in Python, including insertion and extraction of the minimum element. The heap property is maintained using heapify operations after each insertion or extraction.

 

Thank you,

Popular Post:

Give us your feedback!

Your email address will not be published. Required fields are marked *
0 Comments Write Comment