A min heap is a complete binary tree where each parent node is smaller than or equal to its children, ensuring that the smallest element is always at the root. It is commonly used in implementing priority queues.
In a Min Heap, insertion adds a new element at the end of the array. Then, the element is moved up(bubbled up) by swapping with its parent until the smallest element stays at the top, maintaining the heap’s structure.
In a Min Heap, inserting a new element involves placing it at the end of the array and then bubbling up to restore the heap property. In the worst case, the element is compared and swapped with parent nodes up to the root. Since the height of the heap is log n, the number of comparisons and swaps is proportional to log n, making the time complexity O(log n).
In a Min Heap, deletion removes the minimum element at the root. The last element is moved to the root to fill the gap. The heap is restored by bubbling down swapping the root with its smaller child until the min-heap property is reestablished, keeping the smallest element at the top.
Repeat the following steps until the current index (i) reaches a position where no more heapify steps are needed
Calculate the left and right child indices: leftIdx = 2 * i + 1 rightIdx = 2 * i + 2
Compare the current element with its children
If the left child exists (leftIdx < size) and is smaller than the current element (arr[leftIdx] < arr[i]), swap them, and update i to leftIdx.
Otherwise, if the right child exists (rightIdx < size) and is smaller than the current element (arr[rightIdx] < arr[i]), swap them, and update i to rightIdx.
If neither child is smaller than the current element, stop the process.