Naïve Approach-: 2) O (K) Time. The Total Time Complexity Will Be O (K)
Naïve Approach-: 2) O (K) Time. The Total Time Complexity Will Be O (K)
Since deleting an element at any intermediary position in the heap can be costly, so we can simply
replace the element to be deleted by the last element and delete the last element of the Heap.
Since, the last element is now placed at the position of the root node. So, it may not follow
the heap property. Therefore, heapify the last node placed at the position of root.
Heapify is the process of converting a binary tree into a heap data structure.
After each deletion process, the heap gets distorted, so we need to heapify it for each deletion.
A kth least element can be extracted from a min heap by the following two approaches-
1. Naïve Approach-
We will extract the minimum element k times and the last element will be the kth least element.
Each deletion operation will take O(log n) times, so the total time complexity will be O(k * log n).
2. Efficient Approach-
In a min-heap, an element x at ith level has i – 1 ancestors. By the property of min-heaps, these i – 1
ancestors will be smaller than x. This means that x cannot be among the least i – 1 elements of the
heap. Using this property, we can conclude that the kth least element can have a level of at most k.
The size of the min-heap is reduced such that it has only k levels.
We can then obtain the kth least element by our previous strategy of extracting the minimum
element k times.
Since, the heap is reduced to a maximum of 2k – 1, therefore each heapify operation will take O(log
2k) = O(k) time. The total time complexity will be O(k2).
If n >> k, then this approach performs better than the previous one.
For finding the 3rd smallest element, k=3, so we will perform deletion 3 times and extract the 3rd
deleted element.
Source- https://www.geeksforgeeks.org/kth-least-element-in-a-min-heap
Heap(int i = 0)
: n(i)
{
v = vector<int>(n);
}
};
// Generic function to
// swap two integers
void swap(int& a, int& b)
{
int temp = a;
a = b;
b = temp;
}
int main()
{
Heap h(7);
h.v = vector<int>{ 10, 50, 40, 75, 60, 65, 45 };
int k = 2;
cout << findKthSmalles(h, k);
return 0;
}
Output:
40