K’th Smallest/Largest Element in Unsorted Array
Last Updated :
29 Oct, 2023
Given an array arr[] of size N and a number K, where K is smaller than the size of the array. Find the K’th smallest element in the given array. Given that all array elements are distinct.
Examples:
Input: arr[] = {7, 10, 4, 3, 20, 15}, K = 3
Output: 7
Input: arr[] = {7, 10, 4, 3, 20, 15}, K = 4
Output: 10
K’th smallest element in an unsorted array using Sorting:
Sort the given array and return the element at index K-1 in the sorted array.
- Sort the input array in the increasing order
- Return the element at the K-1 index (0 – Based indexing) in the sorted array
Below is the Implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int kthSmallest( int arr[], int N, int K)
{
sort(arr, arr + N);
return arr[K - 1];
}
int main()
{
int arr[] = { 12, 3, 5, 7, 19 };
int N = sizeof (arr) / sizeof (arr[0]), K = 2;
cout << "K'th smallest element is "
<< kthSmallest(arr, N, K);
return 0;
}
|
C
#include <stdio.h>
#include <stdlib.h>
int cmpfunc( const void * a, const void * b)
{
return (*( int *)a - *( int *)b);
}
int kthSmallest( int arr[], int N, int K)
{
qsort (arr, N, sizeof ( int ), cmpfunc);
return arr[K - 1];
}
int main()
{
int arr[] = { 12, 3, 5, 7, 19 };
int N = sizeof (arr) / sizeof (arr[0]), K = 2;
printf ( "K'th smallest element is %d" ,
kthSmallest(arr, N, K));
return 0;
}
|
Java
import java.util.Arrays;
import java.util.Collections;
class GFG {
public static int kthSmallest(Integer[] arr, int K)
{
Arrays.sort(arr);
return arr[K - 1 ];
}
public static void main(String[] args)
{
Integer arr[] = new Integer[] { 12 , 3 , 5 , 7 , 19 };
int K = 2 ;
System.out.print( "K'th smallest element is "
+ kthSmallest(arr, K));
}
}
|
Python3
def kthSmallest(arr, N, K):
arr.sort()
return arr[K - 1 ]
if __name__ = = '__main__' :
arr = [ 12 , 3 , 5 , 7 , 19 ]
N = len (arr)
K = 2
print ( "K'th smallest element is" ,
kthSmallest(arr, N, K))
|
C#
using System;
class GFG {
public static int kthSmallest( int [] arr, int K)
{
Array.Sort(arr);
return arr[K - 1];
}
public static void Main()
{
int [] arr = new int [] { 12, 3, 5, 7, 19 };
int K = 2;
Console.Write( "K'th smallest element"
+ " is " + kthSmallest(arr, K));
}
}
|
Javascript
function kthSmallest(arr, N, K)
{
arr.sort((a,b) => a-b);
return arr[K - 1];
}
let arr = [12, 3, 5, 7, 19];
let N = arr.length, K = 2;
document.write( "K'th smallest element is " + kthSmallest(arr, N, K));
|
PHP
<?php
function kthSmallest( $arr , $N , $K )
{
sort( $arr );
return $arr [ $K - 1];
}
$arr = array (12, 3, 5, 7, 19);
$N = count ( $arr );
$K = 2;
echo "K'th smallest element is " , kthSmallest( $arr , $N , $K );
?>
|
Output
K'th smallest element is 5
Time Complexity: O(N log N)
Auxiliary Space: O(1)
K’th smallest element in an unsorted array using Binary Search on Answer:
To find the kth smallest element using binary search on the answer, we start by defining a search range based on the minimum and maximum values in the input array. In each iteration of binary search, we count the elements smaller than or equal to the midpoint and update the search range accordingly. This process continues until the range collapses to a single element, which is the kth smallest element.
Follow the given steps to solve the problem:
- Intialize low and high to minimum and maximum element of the array denoting the range within which the answer lies.
- Apply Binary Search on this range.
- If the selected element by calculating mid has less than K elements lesser to it then increase the number that is low = mid + 1.
- Otherwise, Decrement the high pointer, i.e high = mid.
- The Binary Search will end when only one element remains in the answer space that would be the answer.
Below is the implementation of above approach:
C++
#include <bits/stdc++.h>
#include <iostream>
using namespace std;
int count(vector< int >& nums, int & mid)
{
int cnt = 0;
for ( int i = 0; i < nums.size(); i++)
if (nums[i] <= mid)
cnt++;
return cnt;
}
int kthSmallest(vector< int > nums, int & k)
{
int low = INT_MAX;
int high = INT_MIN;
for ( int i = 0; i < nums.size(); i++) {
low = min(low, nums[i]);
high = max(high, nums[i]);
}
while (low < high) {
int mid = low + (high - low) / 2;
if (count(nums, mid) < k)
low = mid + 1;
else
high = mid;
}
return low;
}
int main()
{
vector< int > nums{ 1, 4, 5, 3, 19, 3 };
int k = 3;
cout << "K'th smallest element is "
<< kthSmallest(nums, k);
return 0;
}
|
Java
import java.util.Arrays;
import java.util.Collections;
class GFG {
static int count( int [] nums, int mid)
{
int cnt = 0 ;
for ( int i = 0 ; i < nums.length; i++)
if (nums[i] <= mid)
cnt++;
return cnt;
}
static int kthSmallest( int [] nums, int k)
{
int low = Integer.MAX_VALUE;
int high = Integer.MIN_VALUE;
for ( int i = 0 ; i < nums.length; i++) {
low = Math.min(low, nums[i]);
high = Math.max(high, nums[i]);
}
while (low < high) {
int mid = low + (high - low) / 2 ;
if (count(nums, mid) < k)
low = mid + 1 ;
else
high = mid;
}
return low;
}
public static void main(String[] args)
{
int arr[] = { 1 , 4 , 5 , 3 , 19 , 3 };
int k = 3 ;
System.out.print( "Kth smallest element is "
+ kthSmallest(arr, k));
}
}
|
Python3
import sys
def count(nums, mid):
cnt = 0
for i in range ( len (nums)):
if nums[i] < = mid:
cnt + = 1
return cnt
def kthSmallest(nums, k):
low = sys.maxsize
high = - sys.maxsize - 1
for i in range ( len (nums)):
low = min (low, nums[i])
high = max (high, nums[i])
while low < high:
mid = low + (high - low) / / 2
if count(nums, mid) < k:
low = mid + 1
else :
high = mid
return low
if __name__ = = "__main__" :
nums = [ 1 , 4 , 5 , 3 , 19 , 3 ]
k = 3
print ( "K'th smallest element is" , kthSmallest(nums, k))
|
C#
using System;
using System.Collections.Generic;
class GFG {
static int count( int [] nums, int mid)
{
int cnt = 0;
for ( int i = 0; i < nums.Length; i++)
if (nums[i] <= mid)
cnt++;
return cnt;
}
static int kthSmallest( int [] nums, int k)
{
int low = Int32.MaxValue;
int high = Int32.MinValue;
for ( int i = 0; i < nums.Length; i++) {
low = Math.Min(low, nums[i]);
high = Math.Max(high, nums[i]);
}
while (low < high) {
int mid = low + (high - low) / 2;
if (count(nums, mid) < k)
low = mid + 1;
else
high = mid;
}
return low;
}
public static void Main()
{
int [] vec = { 1, 4, 5, 3, 19, 3 };
int K = 3;
Console.WriteLine( "Kth Smallest Element: "
+ kthSmallest(vec, K));
}
}
|
Javascript
function count(nums, mid)
{
var cnt = 0;
for ( var i = 0; i < nums.length; i++)
if (nums[i] <= mid)
cnt++;
return cnt;
}
function kthSmallest(nums,k){
var low = Number. MAX_VALUE;
var high = Number. MIN_VALUE;
for ( var i = 0; i < nums.length; i++)
{
low = Math.min(low, nums[i]);
high = Math.max(high, nums[i]);
}
while (low < high)
{
var mid = Math.floor(low + ((high - low) / 2));
if (count(nums, mid) < k)
low = mid + 1;
else
high = mid;
}
return low;
}
var k = 3;
var nums = [1, 4, 5, 3, 19, 3];
document.write( "K'th smallest element is " + kthSmallest(nums, k));
|
Output
K'th smallest element is 3
Time complexity: O(n * log (mx-mn)), where mn be minimum and mx be maximum element of array.
Auxiliary Space: O(1)
K’th smallest element in an unsorted array using Priority Queue(Max-Heap):
The intuition behind this approach is to maintain a max heap (priority queue) of size K while iterating through the array. Doing this ensures that the max heap always contains the K smallest elements encountered so far. If the size of the max heap exceeds K, remove the largest element this step ensures that the heap maintains the K smallest elements encountered so far. In the end, the max heap’s top element will be the Kth smallest element.
- Initialize a max heap (priority queue) pq.
- For each element in the array:
- Push the element onto the max heap.
- If the size of the max heap exceeds K, pop (remove) the largest element from the max heap. This step ensures that the max heap maintains the K smallest elements encountered so far.
- After processing all elements, the max heap will contain the K smallest elements, with the largest of these K elements at the top.
Below is the Implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int kthSmallest( int arr[], int N, int K)
{
priority_queue< int > pq;
for ( int i = 0; i < N; i++) {
pq.push(arr[i]);
if (pq.size() > K)
pq.pop();
}
return pq.top();
}
int main()
{
int N = 10;
int arr[N] = { 10, 5, 4, 3, 48, 6, 2, 33, 53, 10 };
int K = 4;
cout << "Kth Smallest Element is: "
<< kthSmallest(arr, N, K);
}
|
Java
import java.util.PriorityQueue;
public class KthSmallestElement {
public static int kthSmallest( int [] arr, int N, int K) {
PriorityQueue<Integer> pq = new PriorityQueue<>((a, b) -> b - a);
for ( int i = 0 ; i < N; i++) {
pq.offer(arr[i]);
if (pq.size() > K)
pq.poll();
}
return pq.peek();
}
public static void main(String[] args) {
int N = 10 ;
int [] arr = { 10 , 5 , 4 , 3 , 48 , 6 , 2 , 33 , 53 , 10 };
int K = 4 ;
System.out.println( "Kth Smallest Element is: " + kthSmallest(arr, N, K));
}
}
|
Python3
import heapq
def kthSmallest(arr, K):
max_heap = []
for num in arr:
heapq.heappush(max_heap, - num)
if len (max_heap) > K:
heapq.heappop(max_heap)
return - max_heap[ 0 ]
if __name__ = = "__main__" :
arr = [ 10 , 5 , 4 , 3 , 48 , 6 , 2 , 33 , 53 , 10 ]
K = 4
print ( "Kth Smallest Element is:" , kthSmallest(arr, K))
|
C#
using System;
using System.Collections.Generic;
public class KthSmallestElement
{
public static int KthSmallest( int [] arr, int K)
{
var maxHeap = new SortedSet< int >(Comparer< int >.Create((a, b) => b.CompareTo(a)));
foreach ( var num in arr)
{
maxHeap.Add(-num);
if (maxHeap.Count > K)
maxHeap.Remove(maxHeap.Max);
}
return -maxHeap.Max;
}
public static void Main()
{
int [] arr = { 10, 5, 4, 3, 48, 6, 2, 33, 53, 10 };
int K = 4;
Console.WriteLine( "Kth Smallest Element is: " + KthSmallest(arr, K));
}
}
|
Javascript
function kthSmallest(arr, K) {
let pq = new MaxHeap();
for (let i = 0; i < arr.length; i++) {
pq.push(arr[i]);
if (pq.size() > K)
pq.pop();
}
return pq.top();
}
class MaxHeap {
constructor() {
this .heap = [];
}
push(val) {
this .heap.push(val);
this .heapifyUp( this .heap.length - 1);
}
pop() {
if ( this .heap.length === 0) {
return null ;
}
if ( this .heap.length === 1) {
return this .heap.pop();
}
const root = this .heap[0];
this .heap[0] = this .heap.pop();
this .heapifyDown(0);
return root;
}
top() {
if ( this .heap.length === 0) {
return null ;
}
return this .heap[0];
}
size() {
return this .heap.length;
}
heapifyUp(index) {
while (index > 0) {
const parentIndex = Math.floor((index - 1) / 2);
if ( this .heap[parentIndex] >= this .heap[index]) {
break ;
}
this .swap(parentIndex, index);
index = parentIndex;
}
}
heapifyDown(index) {
const leftChildIndex = 2 * index + 1;
const rightChildIndex = 2 * index + 2;
let largestIndex = index;
if (
leftChildIndex < this .heap.length &&
this .heap[leftChildIndex] > this .heap[largestIndex]
) {
largestIndex = leftChildIndex;
}
if (
rightChildIndex < this .heap.length &&
this .heap[rightChildIndex] > this .heap[largestIndex]
) {
largestIndex = rightChildIndex;
}
if (index !== largestIndex) {
this .swap(index, largestIndex);
this .heapifyDown(largestIndex);
}
}
swap(i, j) {
[ this .heap[i], this .heap[j]] = [ this .heap[j], this .heap[i]];
}
}
const arr = [10, 5, 4, 3, 48, 6, 2, 33, 53, 10];
const K = 4;
console.log( "Kth Smallest Element is: " + kthSmallest(arr, K));
|
Output
Kth Smallest Element is: 5
Time Complexity: O(N * log(K)), The approach efficiently maintains a container of the K smallest elements while iterating through the array, ensuring a time complexity of O(N * log(K)), where N is the number of elements in the array.
Auxiliary Space: O(K)
K’th smallest element in an unsorted array using QuickSelect:
This is an optimization over method 1, if QuickSort is used as a sorting algorithm in first step. In QuickSort, pick a pivot element, then move the pivot element to its correct position and partition the surrounding array. The idea is, not to do complete quicksort, but stop at the point where pivot itself is k’th smallest element. Also, not to recur for both left and right sides of pivot, but recur for one of them according to the position of pivot.
Follow the given steps to solve the problem:
- Run quick sort algorithm on the input array
- In this algorithm pick a pivot element and move it to it’s correct position
- Now, if index of pivot is equal to K then return the value, else if the index of pivot is greater than K, then recur for the left subarray, else recur for the right subarray
- Repeat this process until the element at index K is not found
Below is the Implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int partition( int arr[], int l, int r);
int kthSmallest( int arr[], int l, int r, int K)
{
if (K > 0 && K <= r - l + 1) {
int pos = partition(arr, l, r);
if (pos - l == K - 1)
return arr[pos];
if (pos - l > K - 1)
return kthSmallest(arr, l, pos - 1, K);
return kthSmallest(arr, pos + 1, r,
K - pos + l - 1);
}
return INT_MAX;
}
void swap( int * a, int * b)
{
int temp = *a;
*a = *b;
*b = temp;
}
int partition( int arr[], int l, int r)
{
int x = arr[r], i = l;
for ( int j = l; j <= r - 1; j++) {
if (arr[j] <= x) {
swap(&arr[i], &arr[j]);
i++;
}
}
swap(&arr[i], &arr[r]);
return i;
}
int main()
{
int arr[] = { 12, 3, 5, 7, 4, 19, 26 };
int N = sizeof (arr) / sizeof (arr[0]), K = 3;
cout << "K'th smallest element is "
<< kthSmallest(arr, 0, N - 1, K);
return 0;
}
|
C
#include <limits.h>
#include <stdio.h>
int partition( int arr[], int l, int r);
int kthSmallest( int arr[], int l, int r, int K)
{
if (K > 0 && K <= r - l + 1) {
int pos = partition(arr, l, r);
if (pos - l == K - 1)
return arr[pos];
if (pos - l > K - 1)
return kthSmallest(arr, l, pos - 1, K);
return kthSmallest(arr, pos + 1, r,
K - pos + l - 1);
}
return INT_MAX;
}
void swap( int * a, int * b)
{
int temp = *a;
*a = *b;
*b = temp;
}
int partition( int arr[], int l, int r)
{
int x = arr[r], i = l;
for ( int j = l; j <= r - 1; j++) {
if (arr[j] <= x) {
swap(&arr[i], &arr[j]);
i++;
}
}
swap(&arr[i], &arr[r]);
return i;
}
int main()
{
int arr[] = { 12, 3, 5, 7, 4, 19, 26 };
int N = sizeof (arr) / sizeof (arr[0]), K = 3;
printf ( "K'th smallest element is %d" ,
kthSmallest(arr, 0, N - 1, K));
return 0;
}
|
Java
import java.util.Arrays;
import java.util.Collections;
class GFG {
public static int partition(Integer[] arr, int l, int r)
{
int x = arr[r], i = l;
for ( int j = l; j <= r - 1 ; j++) {
if (arr[j] <= x) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++;
}
}
int temp = arr[i];
arr[i] = arr[r];
arr[r] = temp;
return i;
}
public static int kthSmallest(Integer[] arr, int l,
int r, int K)
{
if (K > 0 && K <= r - l + 1 ) {
int pos = partition(arr, l, r);
if (pos - l == K - 1 )
return arr[pos];
if (pos - l > K - 1 )
return kthSmallest(arr, l, pos - 1 , K);
return kthSmallest(arr, pos + 1 , r,
K - pos + l - 1 );
}
return Integer.MAX_VALUE;
}
public static void main(String[] args)
{
Integer arr[]
= new Integer[] { 12 , 3 , 5 , 7 , 4 , 19 , 26 };
int K = 3 ;
System.out.print(
"K'th smallest element is "
+ kthSmallest(arr, 0 , arr.length - 1 , K));
}
}
|
Python3
import sys
def kthSmallest(arr, l, r, K):
if (K > 0 and K < = r - l + 1 ):
pos = partition(arr, l, r)
if (pos - l = = K - 1 ):
return arr[pos]
if (pos - l > K - 1 ):
return kthSmallest(arr, l, pos - 1 , K)
return kthSmallest(arr, pos + 1 , r,
K - pos + l - 1 )
return sys.maxsize
def partition(arr, l, r):
x = arr[r]
i = l
for j in range (l, r):
if (arr[j] < = x):
arr[i], arr[j] = arr[j], arr[i]
i + = 1
arr[i], arr[r] = arr[r], arr[i]
return i
if __name__ = = "__main__" :
arr = [ 12 , 3 , 5 , 7 , 4 , 19 , 26 ]
N = len (arr)
K = 3
print ( "K'th smallest element is" ,
kthSmallest(arr, 0 , N - 1 , K))
|
C#
using System;
class GFG {
public static int partition( int [] arr, int l, int r)
{
int x = arr[r], i = l;
int temp = 0;
for ( int j = l; j <= r - 1; j++) {
if (arr[j] <= x) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++;
}
}
temp = arr[i];
arr[i] = arr[r];
arr[r] = temp;
return i;
}
public static int kthSmallest( int [] arr, int l, int r,
int K)
{
if (K > 0 && K <= r - l + 1) {
int pos = partition(arr, l, r);
if (pos - l == K - 1)
return arr[pos];
if (pos - l > K - 1)
return kthSmallest(arr, l, pos - 1, K);
return kthSmallest(arr, pos + 1, r,
K - pos + l - 1);
}
return int .MaxValue;
}
public static void Main()
{
int [] arr = { 12, 3, 5, 7, 4, 19, 26 };
int K = 3;
Console.Write(
"K'th smallest element is "
+ kthSmallest(arr, 0, arr.Length - 1, K));
}
}
|
Javascript
function partition( arr , l , r)
{
var x = arr[r], i = l;
for (j = l; j <= r - 1; j++) {
if (arr[j] <= x) {
var temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++;
}
}
var temp = arr[i];
arr[i] = arr[r];
arr[r] = temp;
return i;
}
function kthSmallest( arr , l , r , k) {
if (k > 0 && k <= r - l + 1) {
var pos = partition(arr, l, r);
if (pos - l == k - 1)
return arr[pos];
if (pos - l > k - 1)
return kthSmallest(arr, l, pos - 1, k);
return kthSmallest(arr, pos + 1, r,
k - pos + l - 1);
}
return Number.MAX_VALUE;
}
var arr = [ 12, 3, 5, 7, 4, 19, 26 ];
var k = 3;
document.write( "K'th smallest element is " +
kthSmallest(arr, 0, arr.length - 1, k));
|
Output
K'th smallest element is 5
Time Complexity: O(N2) in worst case and O(N) on average. However if we randomly choose pivots, the probability of worst case could become very less.
Auxiliary Space: O(N)
K’th smallest element in an unsorted array using Counting Sort:
Counting sort is a linear time sorting algorithm that counts the occurrences of each element in an array and uses this information to determine the sorted order. The intuition behind using counting sort to find the kth smallest element is to take advantage of its counting phase, which essentially calculates the cumulative frequencies of elements. By tracking these cumulative frequencies and finding the point where the count reaches or exceeds K can determine the kth smallest element efficiently.
- Find the maximum element in the input array to determine the range of elements.
- Create an array freq of size max_element + 1 to store the frequency of each element in the input array. Initialize all elements of freq to 0.
- Iterate through the input array and update the frequencies of elements in the freq array.
- Initialize a count variable to keep track of the cumulative frequency of elements.
- Iterate through the freq array from 0 to max_element:
- If the frequency of the current element is non-zero, add it to the count.
- Check if count is greater than or equal to k. If it is, return the current element as the kth smallest element.
Below is the Implementation of the above approach:
C++
#include <iostream>
using namespace std;
int kthSmallest( int arr[], int n, int k) {
int max_element = arr[0];
for ( int i = 1; i < n; i++) {
if (arr[i] > max_element) {
max_element = arr[i];
}
}
int freq[max_element + 1] = {0};
for ( int i = 0; i < n; i++) {
freq[arr[i]]++;
}
int count = 0;
for ( int i = 0; i <= max_element; i++) {
if (freq[i] != 0) {
count += freq[i];
if (count >= k) {
return i;
}
}
}
return -1;
}
int main() {
int arr[] = {12,3,5,7,19};
int n = sizeof (arr) / sizeof (arr[0]);
int k = 2;
cout << "The " << k << "th smallest element is " << kthSmallest(arr, n, k) << endl;
return 0;
}
|
Java
import java.util.Arrays;
public class GFG {
static int kthSmallest( int [] arr, int n, int k)
{
int max_element = arr[ 0 ];
for ( int i = 1 ; i < n; i++) {
if (arr[i] > max_element) {
max_element = arr[i];
}
}
int [] freq = new int [max_element + 1 ];
Arrays.fill(freq, 0 );
for ( int i = 0 ; i < n; i++) {
freq[arr[i]]++;
}
int count = 0 ;
for ( int i = 0 ; i <= max_element; i++) {
if (freq[i] != 0 ) {
count += freq[i];
if (count >= k) {
return i;
}
}
}
return - 1 ;
}
public static void main(String[] args)
{
int [] arr = { 12 , 3 , 5 , 7 , 19 };
int n = arr.length;
int k = 2 ;
System.out.println( "The " + k
+ "th smallest element is "
+ kthSmallest(arr, n, k));
}
}
|
Python3
def kth_smallest(arr, k):
max_element = max (arr)
freq = {}
for num in arr:
freq[num] = freq.get(num, 0 ) + 1
count = 0
for i in range (max_element + 1 ):
if i in freq:
count + = freq[i]
if count > = k:
return i
return - 1
arr = [ 12 , 3 , 5 , 7 , 19 ]
k = 2
print ( "The" , k, "th smallest element is" , kth_smallest(arr, k))
|
C#
using System;
public class GFG {
static int KthSmallest( int [] arr, int n, int k) {
int maxElement = arr[0];
for ( int i = 1; i < n; i++) {
if (arr[i] > maxElement) {
maxElement = arr[i];
}
}
int [] freq = new int [maxElement + 1];
for ( int i = 0; i < n; i++) {
freq[arr[i]]++;
}
int count = 0;
for ( int i = 0; i <= maxElement; i++) {
if (freq[i] != 0) {
count += freq[i];
if (count >= k) {
return i;
}
}
}
return -1;
}
static void Main( string [] args) {
int [] arr = { 12, 3, 5, 7, 19 };
int n = arr.Length;
int k = 2;
Console.WriteLine( "The " + k + "th smallest element is " + KthSmallest(arr, n, k));
}
}
|
Javascript
function kthSmallest(arr, k) {
let maxElement = arr[0];
for (let i = 1; i < arr.length; i++) {
if (arr[i] > maxElement) {
maxElement = arr[i];
}
}
let freq = new Array(maxElement + 1).fill(0);
for (let i = 0; i < arr.length; i++) {
freq[arr[i]]++;
}
let count = 0;
for (let i = 0; i <= maxElement; i++) {
if (freq[i] !== 0) {
count += freq[i];
if (count >= k) {
return i;
}
}
}
return -1;
}
const arr = [12, 3, 5, 7, 19];
const k = 2;
console.log(`The ${k}th smallest element is ${kthSmallest(arr, k)}`);
|
Output
The 2th smallest element is 5
Time Complexity:O(N + max_element), where max_element is the maximum element of the array.
Auxiliary Space: O(max_element)
Note: This approach is particularly useful when the range of elements is small, this is because we are declaring a array of size maximum element. If the range of elements is very large, the counting sort approach may not be the most efficient choice.
Related Articles:
Print k largest elements of an array
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...