Site icon Study Algorithms

Kth largest element in an array (Method 1)

Question: Given an unsorted array of integers and a number ‘k’. Return the kth largest element in the array.
Input: arr = {3,2,1,5,6,4}, k = 2
Output: 5

Given an unsorted array of integers, you need to determine the kth largest element. By taking a first glance at the problem we can be sure of one thing. If the array is already sorted in ascending order, we can simply return the element at arr[size – k]. This would give us the kth largest element. This is because the 2nd largest element is the largest element in the array and will exist at arr[size-2]. Since, the array starts at 0.

Let us start solving this problem with one of the most naive methods. By sorting the array. We can use any of the sorting methods we have discussed till now. QuickSort performs the fastest and hence we shall use it.

Once the array is sorted simply return the (size – k)th element.

#include<stdio.h> void swap(int *i, int *j) { int temp = *i; *i = *j; *j = temp; } int partition(int arr[], int start, int end) { int pivot = arr[end]; int i = start; int j = end-1; while(i <= j) { while(arr[i] < pivot) i++; while(arr[j] > pivot) j--; if(i <= j) { swap(&arr[i], &arr[j]); i++; j--; } } swap(&arr[i], &arr[end]); return i; } void performQuickSort(int arr[], int start, int end) { if(start < end) { int p = partition(arr, start, end); performQuickSort(arr, start, p-1); performQuickSort(arr, p+1, end); } } void quickSort(int arr[], int size) { performQuickSort(arr, 0, size-1); } // driver program int main(void) { int i; int arr[10] = {2, 6, 4, 10, 8, 1, 9, 5, 3, 7}; quickSort(arr,10); printf("The 5th largest number in array is:- %d", arr[10 - 5]); return 0; }
Code language: C++ (cpp)

A working implementation of the code can be found at this location.

Note that this is a very naive approach.
Time Complexity:- O(n log(n))
Space Complexity:- O(n)