Given an array arr[] of size N and an integer k, the task is to find the initial index of the array element which will be in the kth position after sorting.
Example :
Input : arr[] = {5, -5, 0, 2}, N = 4, k = 4
Output : 1
Explanation :
After sorting array will be {-5, 0, 2, 5}.
So, at index 4 the element is 5 which was previously at index 1.
Input : arr[] = {2, -1, 9, 7, -2, 3}, N = 6, k = 1
Output : 5
Approach :
The idea is to use a priority queue and push the array elements along with the index and check for the kth position.
Implementation :
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to find the initial
// index of array element
void findindex(int arr[], int N, int k)
{
// Priority queue to store
// array elements with its
// index in pair
priority_queue<pair<int, int> > pq;
// Traversing the array
for(int i = 0; i < N; i++)
{
// Push elements along with index
pq.push(make_pair(arr[i], i+1));
if(pq.size() > k)
{
pq.pop();
}
}
// Printing the initial index
cout << pq.top().second;
}
// Driver Code
int main()
{
int arr[] = {2, -1, 9, 7, -2, 3};
int N = sizeof(arr) / sizeof(arr[0]);
findindex(arr, N, 3);
return 0;
}
Time Complexity : O(N log(k))