Find the initial index of the kth element after sorting

Updated

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;
}
Output

1

Time Complexity : O(N log(k))

Comment
Next tutorial
Mithlesh Upadhyay Published 30 Nov 2026 · 2 min read

Mithlesh Upadhyay is a Computer Science and AI expert from Madhya Pradesh with strong academic background (BE in CSE and M.Tech in AI) and over six years of experience in technical content development. He has contributed tech articles, led teams, and worked in Full Stack Development and Data Science. He founded the w3colleges.org portal for learning resources.

Related tutorials