Min Heap Implementation in PythonA min-heap is a data structure that satisfies the heap property, which states that the value of each node is less than or equal to its children. It means that the minimum value of the heap is always stored at the root. Here is the algorithm for building a min heap:
The insert function takes a heap and a value and adds the value to the heap while maintaining the heap property. The algorithm for the insert function:
Example:Python program to implement this algorithm: Output: [1, 3, 5, 4, 8, 7] The build_heap method starts by copying the input list into the heap array, and then calls the min_heapify method on each non-leaf node in the heap, starting from the bottom and working up. It ensures that the resulting heap satisfies the min-heap property.
Overall, the MinHeap class has a worst-case time complexity of O(n log n) for building the heap, and O(log n) for insertions, extractions, and min heapify operations. Its worst-case space complexity is O(n), due to the need to copy the input list into the heap array when building the heap. One alternative approach is to use a binary heap represented as a binary tree, where each node has at most two children. In this representation, the heap is stored in a list where the parent of a node at index i is at index (i-1)//2, and the left and right children of a node at index i are at indices 2*i+1 and 2*i+2, respectively. Example: Output: [1, 3, 5, 4, 8, 7] Explanation: In this implementation, the __init__ method takes an optional lst argument that is used to build the heap if it is provided. The build_heap method takes a list as input and modifies the heap in-place to ensure that it satisfies the min-heap property. The two approaches are essentially the same. In both cases, we have implemented a binary min-heap using an array to store the heap, and we have used the min_heapify method to ensure that the min-heap property is satisfied after each insertion or deletion operation. The only difference between the two implementations is that in the first approach, the build_heap method takes a list as input and creates a new heap from scratch, whereas in the second approach, the build_heap method modifies an existing heap that is represented as an array. |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India