# K’th Smallest/Largest Element in Unsorted Array

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++

 `// C++ program to find K'th smallest element` `#include ` `using` `namespace` `std;`   `// Function to return K'th smallest element in a given array` `int` `kthSmallest(``int` `arr[], ``int` `N, ``int` `K)` `{` `    ``// Sort the given array` `    ``sort(arr, arr + N);`   `    ``// Return k'th element in the sorted array` `    ``return` `arr[K - 1];` `}`   `// Driver's code` `int` `main()` `{` `    ``int` `arr[] = { 12, 3, 5, 7, 19 };` `    ``int` `N = ``sizeof``(arr) / ``sizeof``(arr[0]), K = 2;`   `    ``// Function call` `    ``cout << ``"K'th smallest element is "` `         ``<< kthSmallest(arr, N, K);` `    ``return` `0;` `}`   `// This code is contributed by Sania Kumari Gupta` `// (kriSania804)`

## C

 `// C program to find K'th smallest element` `#include ` `#include `   `// Compare function for qsort` `int` `cmpfunc(``const` `void``* a, ``const` `void``* b)` `{` `    ``return` `(*(``int``*)a - *(``int``*)b);` `}`   `// Function to return K'th smallest` `// element in a given array` `int` `kthSmallest(``int` `arr[], ``int` `N, ``int` `K)` `{` `    ``// Sort the given array` `    ``qsort``(arr, N, ``sizeof``(``int``), cmpfunc);`   `    ``// Return k'th element in the sorted array` `    ``return` `arr[K - 1];` `}`   `// Driver's code` `int` `main()` `{` `    ``int` `arr[] = { 12, 3, 5, 7, 19 };` `    ``int` `N = ``sizeof``(arr) / ``sizeof``(arr[0]), K = 2;`   `    ``// Function call` `    ``printf``(``"K'th smallest element is %d"``,` `           ``kthSmallest(arr, N, K));` `    ``return` `0;` `}`   `// This code is contributed by Sania Kumari Gupta` `// (kriSania804)`

## Java

 `// Java code for Kth smallest element` `// in an array` `import` `java.util.Arrays;` `import` `java.util.Collections;`   `class` `GFG {` `    ``// Function to return K'th smallest` `    ``// element in a given array` `    ``public` `static` `int` `kthSmallest(Integer[] arr, ``int` `K)` `    ``{` `        ``// Sort the given array` `        ``Arrays.sort(arr);`   `        ``// Return K'th element in` `        ``// the sorted array` `        ``return` `arr[K - ``1``];` `    ``}`   `    ``// driver's code` `    ``public` `static` `void` `main(String[] args)` `    ``{` `        ``Integer arr[] = ``new` `Integer[] { ``12``, ``3``, ``5``, ``7``, ``19` `};` `        ``int` `K = ``2``;`   `        ``// Function call` `        ``System.out.print(``"K'th smallest element is "` `                         ``+ kthSmallest(arr, K));` `    ``}` `}`   `// This code is contributed by Chhavi`

## Python3

 `# Python3 program to find K'th smallest` `# element`   `# Function to return K'th smallest` `# element in a given array`     `def` `kthSmallest(arr, N, K):`   `    ``# Sort the given array` `    ``arr.sort()`   `    ``# Return k'th element in the` `    ``# sorted array` `    ``return` `arr[K``-``1``]`     `# Driver code` `if` `__name__ ``=``=` `'__main__'``:` `    ``arr ``=` `[``12``, ``3``, ``5``, ``7``, ``19``]` `    ``N ``=` `len``(arr)` `    ``K ``=` `2`   `    ``# Function call` `    ``print``(``"K'th smallest element is"``,` `          ``kthSmallest(arr, N, K))`   `# This code is contributed by` `# Shrikant13`

## C#

 `// C# code for Kth smallest element` `// in an array` `using` `System;`   `class` `GFG {`   `    ``// Function to return K'th smallest` `    ``// element in a given array` `    ``public` `static` `int` `kthSmallest(``int``[] arr, ``int` `K)` `    ``{`   `        ``// Sort the given array` `        ``Array.Sort(arr);`   `        ``// Return k'th element in` `        ``// the sorted array` `        ``return` `arr[K - 1];` `    ``}`   `    ``// driver's program` `    ``public` `static` `void` `Main()` `    ``{` `        ``int``[] arr = ``new` `int``[] { 12, 3, 5, 7, 19 };` `        ``int` `K = 2;`   `        ``// Function call` `        ``Console.Write(``"K'th smallest element"` `                      ``+ ``" is "` `+ kthSmallest(arr, K));` `    ``}` `}`   `// This code is contributed by nitin mittal.`

## Javascript

 `// Simple Javascript program to find K'th smallest element`   `// Function to return K'th smallest element in a given array` `function` `kthSmallest(arr, N, K)` `{` `    ``// Sort the given array` `    ``arr.sort((a,b) => a-b);`   `    ``// Return k'th element in the sorted array` `    ``return` `arr[K - 1];` `}`   `// Driver program to test above methods` `    ``let arr = [12, 3, 5, 7, 19];` `    ``let N = arr.length, K = 2;` `    ``document.write(``"K'th smallest element is "` `+ kthSmallest(arr, N, K));`   `//This code is contributed by Mayank Tyagi`

## PHP

 ``

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++

 `// C++ code for the above approach`   `#include ` `#include `   `using` `namespace` `std;`   `int` `count(vector<``int``>& nums, ``int``& mid)` `{` `    ``// function to calculate number of elements less than` `    ``// equal to 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;` `    ``// calculate minimum and maximum the array.` `    ``for` `(``int` `i = 0; i < nums.size(); i++) {` `        ``low = min(low, nums[i]);` `        ``high = max(high, nums[i]);` `    ``}` `    ``// Our answer range lies between minimum and maximum` `    ``// element of the array on which Binary Search is` `    ``// Applied` `    ``while` `(low < high) {` `        ``int` `mid = low + (high - low) / 2;` `        ``/*if the count of number of elements in the array` `          ``less than equal to mid is less than k then` `          ``increase the number. Otherwise decrement the` `          ``number and try to find a better answer.` `        ``*/` `        ``if` `(count(nums, mid) < k)` `            ``low = mid + 1;`   `        ``else` `            ``high = mid;` `    ``}`   `    ``return` `low;` `}`   `// Driver's code` `int` `main()` `{`   `    ``vector<``int``> nums{ 1, 4, 5, 3, 19, 3 };` `    ``int` `k = 3;`   `    ``// Function call` `    ``cout << ``"K'th smallest element is "` `         ``<< kthSmallest(nums, k);` `    ``return` `0;` `}`   `// This code is contributed by garvjuneja98`

## Java

 `// Java code for kth smallest element in an array`   `import` `java.util.Arrays;` `import` `java.util.Collections;`   `class` `GFG {` `    ``static` `int` `count(``int``[] nums, ``int` `mid)` `    ``{` `        ``// function to calculate number of elements less` `        ``// than equal to 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;` `        ``// calculate minimum and maximum the array.` `        ``for` `(``int` `i = ``0``; i < nums.length; i++) {` `            ``low = Math.min(low, nums[i]);` `            ``high = Math.max(high, nums[i]);` `        ``}` `        ``// Our answer range lies between minimum and maximum` `        ``// element of the array on which Binary Search is` `        ``// Applied` `        ``while` `(low < high) {` `            ``int` `mid = low + (high - low) / ``2``;` `            ``/*if the count of number of elements in the` `              ``array less than equal to mid is less than k` `              ``then increase the number. Otherwise decrement` `              ``the number and try to find a better answer.` `            ``*/` `            ``if` `(count(nums, mid) < k)` `                ``low = mid + ``1``;`   `            ``else` `                ``high = mid;` `        ``}`   `        ``return` `low;` `    ``}`   `    ``// Driver's code` `    ``public` `static` `void` `main(String[] args)` `    ``{` `        ``int` `arr[] = { ``1``, ``4``, ``5``, ``3``, ``19``, ``3` `};` `        ``int` `k = ``3``;`   `        ``// Function call` `        ``System.out.print(``"Kth smallest element is "` `                         ``+ kthSmallest(arr, k));` `    ``}` `}`   `// This code is contributed by CodeWithMini`

## Python3

 `# Python3 code for kth smallest element in an array`   `import` `sys`   `# function to calculate number of elements` `# less than equal to mid`     `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`   `    ``# calculate minimum and maximum the array.` `    ``for` `i ``in` `range``(``len``(nums)):` `        ``low ``=` `min``(low, nums[i])` `        ``high ``=` `max``(high, nums[i])`   `        ``# Our answer range lies between minimum and maximum element` `        ``# of the array on which Binary Search is Applied` `    ``while` `low < high:` `        ``mid ``=` `low ``+` `(high ``-` `low) ``/``/` `2` `        ``# if the count of number of elements in the array less than equal` `        ``# to mid is less than k then increase the number. Otherwise decrement` `        ``# the number and try to find a better answer.` `        ``if` `count(nums, mid) < k:` `            ``low ``=` `mid ``+` `1` `        ``else``:` `            ``high ``=` `mid` `    ``return` `low`     `# Driver's code` `if` `__name__ ``=``=` `"__main__"``:` `    ``nums ``=` `[``1``, ``4``, ``5``, ``3``, ``19``, ``3``]` `    ``k ``=` `3`   `    ``# Function call` `    ``print``(``"K'th smallest element is"``, kthSmallest(nums, k))`   `# This code is contributed by Tapesh(tapeshdua420)`

## C#

 `// C# program to implement` `// the above approach`   `using` `System;` `using` `System.Collections.Generic;`   `class` `GFG {` `    ``static` `int` `count(``int``[] nums, ``int` `mid)` `    ``{` `        ``// function to calculate number of elements less` `        ``// than equal to 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;`   `        ``// calculate minimum and maximum the array.` `        ``for` `(``int` `i = 0; i < nums.Length; i++) {` `            ``low = Math.Min(low, nums[i]);` `            ``high = Math.Max(high, nums[i]);` `        ``}`   `        ``// Our answer range lies between minimum` `        ``// and maximum element of the array on which Binary` `        ``// Search is Applied` `        ``while` `(low < high) {` `            ``int` `mid = low + (high - low) / 2;`   `            ``/*if the count of number of elements in the` `                     ``array less than equal to mid is less` `               ``than k then increase the number. Otherwise` `                       ``decrement the number and try to find` `               ``a better answer.` `                     ``*/` `            ``if` `(count(nums, mid) < k)` `                ``low = mid + 1;`   `            ``else` `                ``high = mid;` `        ``}`   `        ``return` `low;` `    ``}`   `    ``// Driver's Code` `    ``public` `static` `void` `Main()` `    ``{`   `        ``// Given array` `        ``int``[] vec = { 1, 4, 5, 3, 19, 3 };`   `        ``// Given K` `        ``int` `K = 3;`   `        ``// Function Call` `        ``Console.WriteLine(``"Kth Smallest Element: "` `                          ``+ kthSmallest(vec, K));` `    ``}` `}`   `// This code is contributed by CodeWithMini`

## Javascript

 `// Javascript program to find the K’th ` `    ``// Smallest/Largest Element in Unsorted Array` `    ``function` `count(nums, mid)` `    ``{` `    ``// function to calculate number of elements less than equal to 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;` `        ``// calculate minimum and maximum the array.` `        ``for``(``var` `i = 0; i < nums.length; i++)` `        ``{` `            ``low = Math.min(low, nums[i]);` `            ``high = Math.max(high, nums[i]);` `        ``}` `        ``// Our answer range lies between minimum and ` `        ``// maximum element of the array on which Binary Search is Applied` `        ``while``(low < high)` `        ``{` `            ``var` `mid = Math.floor(low + ((high - low) / 2));` `           ``/*if the count of number of elements in the array` `           ``less than equal to mid is less than k` `             ``then increase the number. Otherwise ` `             ``decrement the number and try to find a better answer.` `           ``*/` `            ``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));` `    `  `    ``// This code is contributed by shruti456rawal`

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 ` `using` `namespace` `std;`   `// Function to find the kth smallest array element` `int` `kthSmallest(``int` `arr[], ``int` `N, ``int` `K)` `{` `    ``// Create a max heap (priority queue)` `    ``priority_queue<``int``> pq;`   `    ``// Iterate through the array elements` `    ``for` `(``int` `i = 0; i < N; i++) {` `        ``// Push the current element onto the max heap` `        ``pq.push(arr[i]);`   `        ``// If the size of the max heap exceeds K, remove the largest element` `        ``if` `(pq.size() > K)` `            ``pq.pop();` `    ``}`   `    ``// Return the Kth smallest element (top of the max heap)` `    ``return` `pq.top();` `}`   `// Driver's code:` `int` `main()` `{` `    ``int` `N = 10;` `    ``int` `arr[N] = { 10, 5, 4, 3, 48, 6, 2, 33, 53, 10 };` `    ``int` `K = 4;`   `    ``// Function call` `    ``cout << ``"Kth Smallest Element is: "` `         ``<< kthSmallest(arr, N, K);` `}`

## Java

 `import` `java.util.PriorityQueue;`   `public` `class` `KthSmallestElement {`   `    ``// Function to find the kth smallest array element` `    ``public` `static` `int` `kthSmallest(``int``[] arr, ``int` `N, ``int` `K) {` `        ``// Create a max heap (priority queue)` `        ``PriorityQueue pq = ``new` `PriorityQueue<>((a, b) -> b - a);`   `        ``// Iterate through the array elements` `        ``for` `(``int` `i = ``0``; i < N; i++) {` `            ``// Push the current element onto the max heap` `            ``pq.offer(arr[i]);`   `            ``// If the size of the max heap exceeds K, remove the largest element` `            ``if` `(pq.size() > K)` `                ``pq.poll();` `        ``}`   `        ``// Return the Kth smallest element (top of the max heap)` `        ``return` `pq.peek();` `    ``}`   `    ``// Driver's code:` `    ``public` `static` `void` `main(String[] args) {` `        ``int` `N = ``10``;` `        ``int``[] arr = { ``10``, ``5``, ``4``, ``3``, ``48``, ``6``, ``2``, ``33``, ``53``, ``10` `};` `        ``int` `K = ``4``;`   `        ``// Function call` `        ``System.out.println(``"Kth Smallest Element is: "` `+ kthSmallest(arr, N, K));` `    ``}` `}`

## Python3

 `import` `heapq`   `# Function to find the kth smallest array element` `def` `kthSmallest(arr, K):` `    ``# Create a max heap (priority queue)` `    ``max_heap ``=` `[]`   `    ``# Iterate through the array elements` `    ``for` `num ``in` `arr:` `        ``# Push the negative of the current element onto the max heap` `        ``heapq.heappush(max_heap, ``-``num)`   `        ``# If the size of the max heap exceeds K, remove the largest element` `        ``if` `len``(max_heap) > K:` `            ``heapq.heappop(max_heap)`   `    ``# Return the Kth smallest element (top of the max heap, negated)` `    ``return` `-``max_heap[``0``]`   `# Driver's code:` `if` `__name__ ``=``=` `"__main__"``:` `    ``arr ``=` `[``10``, ``5``, ``4``, ``3``, ``48``, ``6``, ``2``, ``33``, ``53``, ``10``]` `    ``K ``=` `4`   `    ``# Function call` `    ``print``(``"Kth Smallest Element is:"``, kthSmallest(arr, K))`

## C#

 `using` `System;` `using` `System.Collections.Generic;`   `public` `class` `KthSmallestElement` `{` `    ``// Function to find the kth smallest array element` `    ``public` `static` `int` `KthSmallest(``int``[] arr, ``int` `K)` `    ``{` `        ``// Create a max heap (priority queue) using a SortedSet` `        ``var` `maxHeap = ``new` `SortedSet<``int``>(Comparer<``int``>.Create((a, b) => b.CompareTo(a)));`   `        ``// Iterate through the array elements` `        ``foreach` `(``var` `num ``in` `arr)` `        ``{` `            ``// Add the current element to the max heap` `            ``maxHeap.Add(-num);`   `            ``// If the size of the max heap exceeds K, remove the largest element` `            ``if` `(maxHeap.Count > K)` `                ``maxHeap.Remove(maxHeap.Max);` `        ``}`   `        ``// Return the Kth smallest element (top of the max heap)` `        ``return` `-maxHeap.Max;` `    ``}`   `    ``// Driver's code:` `    ``public` `static` `void` `Main()` `    ``{` `        ``int``[] arr = { 10, 5, 4, 3, 48, 6, 2, 33, 53, 10 };` `        ``int` `K = 4;`   `        ``// Function call` `        ``Console.WriteLine(``"Kth Smallest Element is: "` `+ KthSmallest(arr, K));` `    ``}` `}`

## Javascript

 `// Function to find the kth smallest array element` `function` `kthSmallest(arr, K) {` `    ``// Create a max heap (priority queue)` `    ``let pq = ``new` `MaxHeap();`   `    ``// Iterate through the array elements` `    ``for` `(let i = 0; i < arr.length; i++) {` `        ``// Push the current element onto the max heap` `        ``pq.push(arr[i]);`   `        ``// If the size of the max heap exceeds K, remove the largest element` `        ``if` `(pq.size() > K)` `            ``pq.pop();` `    ``}`   `    ``// Return the Kth smallest element (top of the max heap)` `    ``return` `pq.top();` `}`   `// MaxHeap class definition` `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]];` `    ``}` `}`   `// Driver's code:` `const arr = [10, 5, 4, 3, 48, 6, 2, 33, 53, 10];` `const K = 4;`   `// Function call` `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++

 `// C++ code for the above approach`   `#include ` `using` `namespace` `std;`   `int` `partition(``int` `arr[], ``int` `l, ``int` `r);`   `// This function returns K'th smallest element in arr[l..r]` `// using QuickSort based method. ASSUMPTION: ALL ELEMENTS IN` `// ARR[] ARE DISTINCT` `int` `kthSmallest(``int` `arr[], ``int` `l, ``int` `r, ``int` `K)` `{` `    ``// If k is smaller than number of elements in array` `    ``if` `(K > 0 && K <= r - l + 1) {`   `        ``// Partition the array around last element and get` `        ``// position of pivot element in sorted array` `        ``int` `pos = partition(arr, l, r);`   `        ``// If position is same as k` `        ``if` `(pos - l == K - 1)` `            ``return` `arr[pos];` `        ``if` `(pos - l > K - 1) ``// If position is more, recur` `                             ``// for left subarray` `            ``return` `kthSmallest(arr, l, pos - 1, K);`   `        ``// Else recur for right subarray` `        ``return` `kthSmallest(arr, pos + 1, r,` `                           ``K - pos + l - 1);` `    ``}`   `    ``// If k is more than number of elements in array` `    ``return` `INT_MAX;` `}`   `void` `swap(``int``* a, ``int``* b)` `{` `    ``int` `temp = *a;` `    ``*a = *b;` `    ``*b = temp;` `}`   `// Standard partition process of QuickSort(). It considers` `// the last element as pivot and moves all smaller element` `// to left of it and greater elements to right` `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;` `}`   `// Driver's code` `int` `main()` `{` `    ``int` `arr[] = { 12, 3, 5, 7, 4, 19, 26 };` `    ``int` `N = ``sizeof``(arr) / ``sizeof``(arr[0]), K = 3;`   `    ``// Function call` `    ``cout << ``"K'th smallest element is "` `         ``<< kthSmallest(arr, 0, N - 1, K);` `    ``return` `0;` `}`

## C

 `// C code for the above approach`   `#include ` `#include `   `int` `partition(``int` `arr[], ``int` `l, ``int` `r);`   `// This function returns K'th smallest element in arr[l..r]` `// using QuickSort based method. ASSUMPTION: ALL ELEMENTS IN` `// ARR[] ARE DISTINCT` `int` `kthSmallest(``int` `arr[], ``int` `l, ``int` `r, ``int` `K)` `{` `    ``// If k is smaller than number of elements in array` `    ``if` `(K > 0 && K <= r - l + 1) {`   `        ``// Partition the array around last element and get` `        ``// position of pivot element in sorted array` `        ``int` `pos = partition(arr, l, r);`   `        ``// If position is same as k` `        ``if` `(pos - l == K - 1)` `            ``return` `arr[pos];` `        ``if` `(pos - l > K - 1) ``// If position is more, recur` `                             ``// for left subarray` `            ``return` `kthSmallest(arr, l, pos - 1, K);`   `        ``// Else recur for right subarray` `        ``return` `kthSmallest(arr, pos + 1, r,` `                           ``K - pos + l - 1);` `    ``}`   `    ``// If k is more than number of elements in array` `    ``return` `INT_MAX;` `}`   `void` `swap(``int``* a, ``int``* b)` `{` `    ``int` `temp = *a;` `    ``*a = *b;` `    ``*b = temp;` `}`   `// Standard partition process of QuickSort(). It considers` `// the last element as pivot and moves all smaller element` `// to left of it and greater elements to right` `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;` `}`   `// Driver's code` `int` `main()` `{` `    ``int` `arr[] = { 12, 3, 5, 7, 4, 19, 26 };` `    ``int` `N = ``sizeof``(arr) / ``sizeof``(arr[0]), K = 3;`   `    ``// Function call` `    ``printf``(``"K'th smallest element is %d"``,` `           ``kthSmallest(arr, 0, N - 1, K));` `    ``return` `0;` `}`

## Java

 `// Java code for kth smallest element in an array`   `import` `java.util.Arrays;` `import` `java.util.Collections;`   `class` `GFG {` `    ``// Standard partition process of QuickSort.` `    ``// It considers the last element as pivot` `    ``// and moves all smaller element to left of` `    ``// it and greater elements to right` `    ``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) {`   `                ``// Swapping arr[i] and arr[j]` `                ``int` `temp = arr[i];` `                ``arr[i] = arr[j];` `                ``arr[j] = temp;`   `                ``i++;` `            ``}` `        ``}`   `        ``// Swapping arr[i] and arr[r]` `        ``int` `temp = arr[i];` `        ``arr[i] = arr[r];` `        ``arr[r] = temp;`   `        ``return` `i;` `    ``}`   `    ``// This function returns k'th smallest element` `    ``// in arr[l..r] using QuickSort based method.` `    ``// ASSUMPTION: ALL ELEMENTS IN ARR[] ARE DISTINCT` `    ``public` `static` `int` `kthSmallest(Integer[] arr, ``int` `l,` `                                  ``int` `r, ``int` `K)` `    ``{` `        ``// If k is smaller than number of elements` `        ``// in array` `        ``if` `(K > ``0` `&& K <= r - l + ``1``) {`   `            ``// Partition the array around last` `            ``// element and get position of pivot` `            ``// element in sorted array` `            ``int` `pos = partition(arr, l, r);`   `            ``// If position is same as k` `            ``if` `(pos - l == K - ``1``)` `                ``return` `arr[pos];`   `            ``// If position is more, recur for` `            ``// left subarray` `            ``if` `(pos - l > K - ``1``)` `                ``return` `kthSmallest(arr, l, pos - ``1``, K);`   `            ``// Else recur for right subarray` `            ``return` `kthSmallest(arr, pos + ``1``, r,` `                               ``K - pos + l - ``1``);` `        ``}`   `        ``// If k is more than number of elements` `        ``// in array` `        ``return` `Integer.MAX_VALUE;` `    ``}`   `    ``// Driver's code` `    ``public` `static` `void` `main(String[] args)` `    ``{` `        ``Integer arr[]` `            ``= ``new` `Integer[] { ``12``, ``3``, ``5``, ``7``, ``4``, ``19``, ``26` `};` `        ``int` `K = ``3``;`   `        ``// Function call` `        ``System.out.print(` `            ``"K'th smallest element is "` `            ``+ kthSmallest(arr, ``0``, arr.length - ``1``, K));` `    ``}` `}`   `// This code is contributed by Chhavi`

## Python3

 `# Python3 code for the above approach`   `# This function returns k'th smallest element` `# in arr[l..r] using QuickSort based method.` `# ASSUMPTION: ALL ELEMENTS IN ARR[] ARE DISTINCT` `import` `sys`     `def` `kthSmallest(arr, l, r, K):`   `    ``# If k is smaller than number of` `    ``# elements in array` `    ``if` `(K > ``0` `and` `K <``=` `r ``-` `l ``+` `1``):`   `        ``# Partition the array around last` `        ``# element and get position of pivot` `        ``# element in sorted array` `        ``pos ``=` `partition(arr, l, r)`   `        ``# If position is same as k` `        ``if` `(pos ``-` `l ``=``=` `K ``-` `1``):` `            ``return` `arr[pos]` `        ``if` `(pos ``-` `l > K ``-` `1``):  ``# If position is more,` `                              ``# recur for left subarray` `            ``return` `kthSmallest(arr, l, pos ``-` `1``, K)`   `        ``# Else recur for right subarray` `        ``return` `kthSmallest(arr, pos ``+` `1``, r,` `                           ``K ``-` `pos ``+` `l ``-` `1``)`   `    ``# If k is more than number of` `    ``# elements in array` `    ``return` `sys.maxsize`   `# Standard partition process of QuickSort().` `# It considers the last element as pivot and` `# moves all smaller element to left of it` `# and greater elements to right`     `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`     `# Driver's Code` `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))`   `# This code is contributed by ita_c`

## C#

 `// C# code for kth smallest element` `// in an array`   `using` `System;`   `class` `GFG {`   `    ``// Standard partition process of QuickSort.` `    ``// It considers the last element as pivot` `    ``// and moves all smaller element to left of` `    ``// it and greater elements to right` `    ``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) {` `                ``// Swapping arr[i] and arr[j]` `                ``temp = arr[i];` `                ``arr[i] = arr[j];` `                ``arr[j] = temp;`   `                ``i++;` `            ``}` `        ``}`   `        ``// Swapping arr[i] and arr[r]` `        ``temp = arr[i];` `        ``arr[i] = arr[r];` `        ``arr[r] = temp;`   `        ``return` `i;` `    ``}`   `    ``// This function returns k'th smallest` `    ``// element in arr[l..r] using QuickSort` `    ``// based method. ASSUMPTION: ALL ELEMENTS` `    ``// IN ARR[] ARE DISTINCT` `    ``public` `static` `int` `kthSmallest(``int``[] arr, ``int` `l, ``int` `r,` `                                  ``int` `K)` `    ``{` `        ``// If k is smaller than number` `        ``// of elements in array` `        ``if` `(K > 0 && K <= r - l + 1) {` `            ``// Partition the array around last` `            ``// element and get position of pivot` `            ``// element in sorted array` `            ``int` `pos = partition(arr, l, r);`   `            ``// If position is same as k` `            ``if` `(pos - l == K - 1)` `                ``return` `arr[pos];`   `            ``// If position is more, recur for` `            ``// left subarray` `            ``if` `(pos - l > K - 1)` `                ``return` `kthSmallest(arr, l, pos - 1, K);`   `            ``// Else recur for right subarray` `            ``return` `kthSmallest(arr, pos + 1, r,` `                               ``K - pos + l - 1);` `        ``}`   `        ``// If k is more than number` `        ``// of elements in array` `        ``return` `int``.MaxValue;` `    ``}`   `    ``// Driver's Code` `    ``public` `static` `void` `Main()` `    ``{` `        ``int``[] arr = { 12, 3, 5, 7, 4, 19, 26 };` `        ``int` `K = 3;`   `        ``// Function call` `        ``Console.Write(` `            ``"K'th smallest element is "` `            ``+ kthSmallest(arr, 0, arr.Length - 1, K));` `    ``}` `}`   `// This code is contributed` `// by 29AjayKumar`

## Javascript

 `// JavaScript code for kth smallest` `// element in an array`   `    ``// Standard partition process of QuickSort.` `    ``// It considers the last element as pivot` `    ``// and moves all smaller element to left of` `    ``// it and greater elements to right` `    ``function` `partition( arr , l , r) ` `    ``{` `        ``var` `x = arr[r], i = l;` `        ``for` `(j = l; j <= r - 1; j++) {` `            ``if` `(arr[j] <= x) {` `                ``// Swapping arr[i] and arr[j]` `                ``var` `temp = arr[i];` `                ``arr[i] = arr[j];` `                ``arr[j] = temp;`   `                ``i++;` `            ``}` `        ``}`   `        ``// Swapping arr[i] and arr[r]` `        ``var` `temp = arr[i];` `        ``arr[i] = arr[r];` `        ``arr[r] = temp;`   `        ``return` `i;` `    ``}`   `    ``// This function returns k'th smallest element` `    ``// in arr[l..r] using QuickSort based method.` `    ``// ASSUMPTION: ALL ELEMENTS IN ARR ARE DISTINCT` `    ``function` `kthSmallest( arr , l , r , k) {` `        ``// If k is smaller than number of elements` `        ``// in array` `        ``if` `(k > 0 && k <= r - l + 1) {` `            ``// Partition the array around last` `            ``// element and get position of pivot` `            ``// element in sorted array` `            ``var` `pos = partition(arr, l, r);`   `            ``// If position is same as k` `            ``if` `(pos - l == k - 1)` `                ``return` `arr[pos];`   `            ``// If position is more, recur for` `            ``// left subarray` `            ``if` `(pos - l > k - 1)` `                ``return` `kthSmallest(arr, l, pos - 1, k);`   `            ``// Else recur for right subarray` `            ``return` `kthSmallest(arr, pos + 1, r, ` `            ``k - pos + l - 1);` `        ``}`   `        ``// If k is more than number of elements` `        ``// in array` `        ``return` `Number.MAX_VALUE;` `    ``}`   `    ``// Driver program to test above methods` `    `  `        ``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));`   `// This code contributed by Rajput-Ji`

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 ` `using` `namespace` `std;`   `// This function returns the kth smallest element in an array` `int` `kthSmallest(``int` `arr[], ``int` `n, ``int` `k) {` `    ``// First, find the maximum element in the array` `    ``int` `max_element = arr[0];` `    ``for` `(``int` `i = 1; i < n; i++) {` `        ``if` `(arr[i] > max_element) {` `            ``max_element = arr[i];` `        ``}` `    ``}`   `    ``// Create an array to store the frequency of each ` `   ``// element in the input array` `    ``int` `freq[max_element + 1] = {0};` `    ``for` `(``int` `i = 0; i < n; i++) {` `        ``freq[arr[i]]++;` `    ``}`   `    ``// Keep track of the cumulative frequency of elements ` `   ``// in the input array` `    ``int` `count = 0;` `    ``for` `(``int` `i = 0; i <= max_element; i++) {` `        ``if` `(freq[i] != 0) {` `            ``count += freq[i];` `            ``if` `(count >= k) {` `                ``// If we have seen k or more elements, ` `              ``// return the current element` `                ``return` `i;` `            ``}` `        ``}` `    ``}` `    ``return` `-1;` `}`   `// Driver Code` `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 {`   `    ``// This function returns the kth smallest element in an` `    ``// array` `    ``static` `int` `kthSmallest(``int``[] arr, ``int` `n, ``int` `k)` `    ``{` `        ``// First, find the maximum element in the array` `        ``int` `max_element = arr[``0``];` `        ``for` `(``int` `i = ``1``; i < n; i++) {` `            ``if` `(arr[i] > max_element) {` `                ``max_element = arr[i];` `            ``}` `        ``}`   `        ``// Create an array to store the frequency of each` `        ``// element in the input array` `        ``int``[] freq = ``new` `int``[max_element + ``1``];` `        ``Arrays.fill(freq, ``0``);` `        ``for` `(``int` `i = ``0``; i < n; i++) {` `            ``freq[arr[i]]++;` `        ``}`   `        ``// Keep track of the cumulative frequency of` `        ``// elements in the input array` `        ``int` `count = ``0``;` `        ``for` `(``int` `i = ``0``; i <= max_element; i++) {` `            ``if` `(freq[i] != ``0``) {` `                ``count += freq[i];` `                ``if` `(count >= k) {` `                    ``// If we have seen k or more elements,` `                    ``// return the current element` `                    ``return` `i;` `                ``}` `            ``}` `        ``}` `        ``return` `-``1``;` `    ``}`   `    ``// Driver Code` `    ``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));` `    ``}` `}`   `// This code is contributed by akshitaguprzj3`

## Python3

 `# Python3 code for kth smallest element in an array`   `# function returns the kth smallest element in an array` `def` `kth_smallest(arr, k):` `    ``# First, find the maximum element in the array` `    ``max_element ``=` `max``(arr)`   `    ``# Create a dictionary to store the frequency of each ` `    ``# element in the input array` `    ``freq ``=` `{}` `    ``for` `num ``in` `arr:` `        ``freq[num] ``=` `freq.get(num, ``0``) ``+` `1`   `    ``# Keep track of the cumulative frequency of elements ` `    ``# in the input array` `    ``count ``=` `0` `    ``for` `i ``in` `range``(max_element ``+` `1``):` `        ``if` `i ``in` `freq:` `            ``count ``+``=` `freq[i]` `            ``if` `count >``=` `k:` `                ``# If we have seen k or more elements, ` `                ``# return the current element` `                ``return` `i`   `    ``return` `-``1`   `# Driver Code` `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 {` `    ``// This function returns the kth smallest element in an array` `    ``static` `int` `KthSmallest(``int``[] arr, ``int` `n, ``int` `k) {` `        ``// First, find the maximum element in the array` `        ``int` `maxElement = arr[0];` `        ``for` `(``int` `i = 1; i < n; i++) {` `            ``if` `(arr[i] > maxElement) {` `                ``maxElement = arr[i];` `            ``}` `        ``}`   `        ``// Create an array to store the frequency of each ` `        ``// element in the input array` `        ``int``[] freq = ``new` `int``[maxElement + 1];` `        ``for` `(``int` `i = 0; i < n; i++) {` `            ``freq[arr[i]]++;` `        ``}`   `        ``// Keep track of the cumulative frequency of elements ` `        ``// in the input array` `        ``int` `count = 0;` `        ``for` `(``int` `i = 0; i <= maxElement; i++) {` `            ``if` `(freq[i] != 0) {` `                ``count += freq[i];` `                ``if` `(count >= k) {` `                    ``// If we have seen k or more elements, ` `                    ``// return the current element` `                    ``return` `i;` `                ``}` `            ``}` `        ``}` `        ``return` `-1;` `    ``}`   `    ``// Driver Code` `    ``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 to find the kth smallest element in an array` `function` `kthSmallest(arr, k) {` `    ``// First, find the maximum element in the array` `    ``let maxElement = arr[0];` `    ``for` `(let i = 1; i < arr.length; i++) {` `        ``if` `(arr[i] > maxElement) {` `            ``maxElement = arr[i];` `        ``}` `    ``}`   `    ``// Create an array to store the frequency of each element in the input array` `    ``let freq = ``new` `Array(maxElement + 1).fill(0);` `    ``for` `(let i = 0; i < arr.length; i++) {` `        ``freq[arr[i]]++;` `    ``}`   `    ``// Keep track of the cumulative frequency of elements in the input array` `    ``let count = 0;` `    ``for` `(let i = 0; i <= maxElement; i++) {` `        ``if` `(freq[i] !== 0) {` `            ``count += freq[i];` `            ``if` `(count >= k) {` `                ``// If we have seen k or more elements, return the current element` `                ``return` `i;` `            ``}` `        ``}` `    ``}` `    ``return` `-1; ``// kth smallest element not found` `}`   `// Driver code` `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

Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!

Previous
Next