kth Largest Element in an Array

Problem

Given an array of positive integers. Find the n(th) largest element in the array.

Solution

Sort the array in decreasing order then loop through the sorted array while counting unique elements then stop when the count is equal to (n). In the code below we will assume the array is already sorted. You can refer to the following post for more information about merge sort which you can use to efficiently sort the array in O(nlogn) time complexity

Code

Here is the C++ code to do that assuming the array is already sorted in decreasing order

Tags:,

Add a Comment

Your email address will not be published. Required fields are marked *