# K’th Smallest/Largest Element in Unsorted Array

• Difficulty Level : Medium
• Last Updated : 24 Jan, 2023

Given an array 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

We have discussed a similar problem to print k largest elements

## 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.

Follow the given steps to solve the problem:

• 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 ``#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)`

## 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)`

## 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.`

## PHP

 ``

## 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`

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 set data structure:

Set data structure can be used to find the kth smallest element as it stores the distinct elements in sorted order. Set can be used because it is mentioned in the question that all the elements in the array are distinct.

Follow the given steps to solve the problem:

• Insert all array elements into the set
• Advance the iterator to the Kth element in the set
• Return the value of the element at which the iterator is pointing

Below is the Implementation of the above approach:

## C++

 `// C++ code for the above approach` `#include ``using` `namespace` `std;` `int` `main()``{``    ``int` `arr[] = { 12, 3, 5, 7, 19 };``    ``int` `N = ``sizeof``(arr) / ``sizeof``(arr[0]);``    ``int` `K = 4;` `    ``set<``int``> s(arr, arr + N);` `    ``// s.begin() returns a pointer to first``    ``// element in the set``    ``set<``int``>::iterator itr = s.begin();` `    ``advance(itr, K - 1); ``// itr points to kth element in set` `    ``cout << *itr << ``"\n"``;` `    ``return` `0;``}`

## Java

 `// Java code for the above approach` `import` `java.util.*;` `class` `GFG {` `    ``public` `static` `void` `main(String[] args)``    ``{``        ``int``[] arr = { ``12``, ``3``, ``5``, ``7``, ``19` `};``        ``int` `N = arr.length;``        ``int` `K = ``4``;` `        ``// since counting starts from 0 so to find kth``        ``// element we need to reduce K by 1``        ``K--;` `        ``// for storing elements in sorted form``        ``// in set we will use TreeSet``        ``Set s = ``new` `TreeSet();` `        ``// Adding elements to set``        ``for` `(``int` `i = ``0``; i < N; i++)``            ``s.add(arr[i]);` `        ``// Use iterator method of Iterator``        ``// for the traversal``        ``Iterator itr = s.iterator();` `        ``while` `(K > ``0``) {``            ``itr.next();``            ``K--;``        ``} ``// itr points to the Kth element in the set` `        ``System.out.println(itr.next());``    ``}``}` `// This code is contributed by Abhijeet Kumar(abhijeet19403)`

## Python3

 `# Python3 code for the above approach` `if` `__name__ ``=``=` `'__main__'``:``    ``arr ``=` `[``12``, ``3``, ``5``, ``7``, ``19``]``    ``N ``=` `len``(arr)``    ``K ``=` `4` `    ``s ``=` `set``(arr)` `    ``for` `itr ``in` `s:``        ``if` `K ``=``=` `1``:``            ``print``(itr)  ``# itr is the Kth element in the set``            ``break``        ``K ``-``=` `1` `# This code is contributed by Abhijeet Kumar(abhijeet19403)`

## C#

 `// C# code for the above approach` `using` `System;``using` `System.Collections.Generic;` `class` `GFG {` `    ``// Driver code``    ``public` `static` `void` `Main()``    ``{` `        ``int``[] arr = { 12, 3, 5, 7, 19 };``        ``int` `N = arr.Length;``        ``int` `K = 4;` `        ``SortedSet<``int``> s = ``new` `SortedSet<``int``>();``        ``foreach``(``int` `i ``in` `arr) s.Add(i);` `        ``foreach``(``int` `itr ``in` `s)``        ``{``            ``if` `(K == 1) {``                ``Console.WriteLine(itr);``                ``// itr is the kth element in the set``                ``break``;``            ``}``            ``K--;``        ``}``    ``}``}` `// This code is contributed by Abhijeet Kumar(abhijeet19403)`

Output

`12`

Time Complexity:  O(N*log N)
Auxiliary Space: O(N)

## K’th smallest element in an unsorted array using heap data structure:

### K’th smallest element in an unsorted array using Min-Heap

Min-Heap can be used to find the kth smallest element, by inserting all the elements into Min-Heap and then and call extractMin() function K times.

Follow the given steps to solve the problem:

• Insert all the array elements into the Min-Heap
• Call extractMin() function K times
• Return the value obtained at the last call of extractMin() function

Below is the Implementation of the above approach:

## C++

 `// C++ program to find K'th smallest element using min heap` `#include ``#include ``using` `namespace` `std;` `// Prototype of a utility function to swap two integers``void` `swap(``int``* x, ``int``* y);` `// A class for Min Heap``class` `MinHeap {` `    ``int``* harr; ``// pointer to array of elements in heap``    ``int` `capacity; ``// maximum possible size of min heap``    ``int` `heap_size; ``// Current number of elements in min heap``public``:``    ``MinHeap(``int` `a[], ``int` `size); ``// Constructor` `    ``// To minheapify subtree rooted with index i``    ``void` `MinHeapify(``int` `i);``    ``int` `parent(``int` `i) { ``return` `(i - 1) / 2; }``    ``int` `left(``int` `i) { ``return` `(2 * i + 1); }``    ``int` `right(``int` `i) { ``return` `(2 * i + 2); }` `    ``int` `extractMin(); ``// extracts root (minimum) element``    ``int` `getMin() { ``return` `harr[0]; } ``// Returns minimum``};` `MinHeap::MinHeap(``int` `a[], ``int` `size)``{``    ``heap_size = size;``    ``harr = a; ``// store address of array``    ``int` `i = (heap_size - 1) / 2;``    ``while` `(i >= 0) {``        ``MinHeapify(i);``        ``i--;``    ``}``}` `// Method to remove minimum element (or root) from min heap``int` `MinHeap::extractMin()``{``    ``if` `(heap_size == 0)``        ``return` `INT_MAX;` `    ``// Store the minimum value.``    ``int` `root = harr[0];` `    ``// If there are more than 1 items, move the last item to``    ``// root and call heapify.``    ``if` `(heap_size > 1) {``        ``harr[0] = harr[heap_size - 1];``        ``MinHeapify(0);``    ``}``    ``heap_size--;` `    ``return` `root;``}` `// A recursive method to heapify a subtree with root at``// given index This method assumes that the subtrees are``// already heapified``void` `MinHeap::MinHeapify(``int` `i)``{``    ``int` `l = left(i);``    ``int` `r = right(i);``    ``int` `smallest = i;` `    ``if` `(l < heap_size && harr[l] < harr[i])``        ``smallest = l;` `    ``if` `(r < heap_size && harr[r] < harr[smallest])``        ``smallest = r;` `    ``if` `(smallest != i) {``        ``swap(&harr[i], &harr[smallest]);``        ``MinHeapify(smallest);``    ``}``}` `// A utility function to swap two elements``void` `swap(``int``* x, ``int``* y)``{``    ``int` `temp = *x;``    ``*x = *y;``    ``*y = temp;``}` `// Function to return k'th smallest element in a given array``int` `kthSmallest(``int` `arr[], ``int` `N, ``int` `K)``{``    ``// Build a heap of n elements: O(n) time``    ``MinHeap mh(arr, N);` `    ``// Do extract min (K-1) times``    ``for` `(``int` `i = 0; i < K - 1; i++)``        ``mh.extractMin();` `    ``// Return root``    ``return` `mh.getMin();``}` `// 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;``}`

## Java

 `// Java program to find K'th smallest element using min heap``import` `java.util.*;``public` `class` `GFG {` `    ``// A class for Max Heap``    ``class` `MinHeap {``        ``int``[] harr; ``// pointer to array of elements in heap``        ``int` `capacity; ``// maximum possible size of min heap``        ``int` `heap_size; ``// Current number of elements in min``                       ``// heap` `        ``int` `parent(``int` `i) { ``return` `(i - ``1``) / ``2``; }``        ``int` `left(``int` `i) { ``return` `((``2` `* i) + ``1``); }``        ``int` `right(``int` `i) { ``return` `((``2` `* i) + ``2``); }``        ``int` `getMin() { ``return` `harr[``0``]; } ``// Returns minimum` `        ``// to replace root with new node x and heapify() new``        ``// root``        ``void` `replaceMax(``int` `x)``        ``{``            ``this``.harr[``0``] = x;``            ``minHeapify(``0``);``        ``}``        ``MinHeap(``int` `a[], ``int` `size)``        ``{``            ``heap_size = size;``            ``harr = a; ``// store address of array``            ``int` `i = (heap_size - ``1``) / ``2``;``            ``while` `(i >= ``0``) {``                ``minHeapify(i);``                ``i--;``            ``}``        ``}` `        ``// Method to remove maximum element (or root) from``        ``// min heap``        ``int` `extractMin()``        ``{``            ``if` `(heap_size == ``0``)``                ``return` `Integer.MAX_VALUE;` `            ``// Store the maximum value.``            ``int` `root = harr[``0``];` `            ``// If there are more than 1 items, move the last``            ``// item to root and call heapify.``            ``if` `(heap_size > ``1``) {``                ``harr[``0``] = harr[heap_size - ``1``];``                ``minHeapify(``0``);``            ``}``            ``heap_size--;``            ``return` `root;``        ``}` `        ``// A recursive method to heapify a subtree with root``        ``// at given index This method assumes that the``        ``// subtrees are already heapified``        ``void` `minHeapify(``int` `i)``        ``{``            ``int` `l = left(i);``            ``int` `r = right(i);``            ``int` `smallest = i;``            ``if` `(l < heap_size && harr[l] < harr[i])``                ``smallest = l;``            ``if` `(r < heap_size && harr[r] < harr[smallest])``                ``smallest = r;``            ``if` `(smallest != i) {``                ``int` `t = harr[i];``                ``harr[i] = harr[smallest];``                ``harr[smallest] = t;``                ``minHeapify(smallest);``            ``}``        ``}``    ``};` `    ``// Function to return k'th largest element in a given``    ``// array``    ``int` `kthSmallest(``int` `arr[], ``int` `N, ``int` `K)``    ``{` `        ``// Build a heap of first k elements: O(k) time``        ``MinHeap mh = ``new` `MinHeap(arr, N);` `        ``// Process remaining n-k elements. If current``        ``// element is smaller than root, replace root with``        ``// current element``        ``for` `(``int` `i = ``0``; i < K - ``1``; i++)``            ``mh.extractMin();` `        ``// Return root``        ``return` `mh.getMin();``    ``}` `    ``// Driver's code``    ``public` `static` `void` `main(String[] args)``    ``{``        ``int` `arr[] = { ``12``, ``3``, ``5``, ``7``, ``19` `};``        ``int` `N = arr.length, K = ``2``;``        ``GFG gfg = ``new` `GFG();` `        ``// Function call``        ``System.out.print(``"K'th smallest element is "``                         ``+ gfg.kthSmallest(arr, N, K));``    ``}``}` `// This code is contributed by avanitrachhadiya2155`

## Python3

 `# Python3 program to find K'th smallest element``# using min heap` `# Class for Min Heap`  `class` `MinHeap:` `    ``# Constructor``    ``def` `__init__(``self``, a, size):` `        ``# list of elements in the heap``        ``self``.harr ``=` `a` `        ``# maximum possible size of min heap``        ``self``.capacity ``=` `None` `        ``# current number of elements in min heap``        ``self``.heap_size ``=` `size` `        ``i ``=` `int``((``self``.heap_size ``-` `1``) ``/` `2``)``        ``while` `i >``=` `0``:``            ``self``.minHeapify(i)``            ``i ``-``=` `1` `    ``def` `parent(``self``, i):``        ``return` `(i ``-` `1``) ``/` `2` `    ``def` `left(``self``, i):``        ``return` `2` `*` `i ``+` `1` `    ``def` `right(``self``, i):``        ``return` `2` `*` `i ``+` `2` `    ``# Returns minimum``    ``def` `getMin(``self``):``        ``return` `self``.harr[``0``]` `    ``# Method to remove minimum element (or root)``    ``# from min heap``    ``def` `extractMin(``self``):``        ``if` `self``.heap_size ``=``=` `0``:``            ``return` `float``(``"inf"``)` `        ``# Store the minimum value``        ``root ``=` `self``.harr[``0``]` `        ``# If there are more than 1 items, move the last item``        ``# to root and call heapify``        ``if` `self``.heap_size > ``1``:``            ``self``.harr[``0``] ``=` `self``.harr[``self``.heap_size ``-` `1``]``            ``self``.minHeapify(``0``)``        ``self``.heap_size ``-``=` `1``        ``return` `root` `    ``# A recursive method to heapify a subtree with root at``    ``# given index. This method assumes that the subtrees``    ``# are already heapified``    ``def` `minHeapify(``self``, i):``        ``l ``=` `self``.left(i)``        ``r ``=` `self``.right(i)``        ``smallest ``=` `i``        ``if` `((l < ``self``.heap_size) ``and``                ``(``self``.harr[l] < ``self``.harr[i])):``            ``smallest ``=` `l``        ``if` `((r < ``self``.heap_size) ``and``                ``(``self``.harr[r] < ``self``.harr[smallest])):``            ``smallest ``=` `r``        ``if` `smallest !``=` `i:``            ``self``.harr[i], ``self``.harr[smallest] ``=` `(``                ``self``.harr[smallest], ``self``.harr[i])``            ``self``.minHeapify(smallest)` `# Function to return k'th smallest element in a given array`  `def` `kthSmallest(arr, N, K):` `    ``# Build a heap of n elements in O(n) time``    ``mh ``=` `MinHeap(arr, N)` `    ``# Do extract min (k-1) times``    ``for` `i ``in` `range``(K ``-` `1``):``        ``mh.extractMin()` `    ``# Return root``    ``return` `mh.getMin()`  `# Driver's 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 Kevin Joshi`

## C#

 `using` `System;``public` `class` `GFG {` `    ``public` `class` `MinHeap {``        ``int``[] harr; ``// Pointer to array of elements in heap``        ``//    int capacity; // maximum possible size of min``        ``//    heap``        ``int` `heap_size; ``// Current number of elements in min``                       ``// heap` `        ``int` `parent(``int` `i) { ``return` `(i - 1) / 2; }``        ``int` `left(``int` `i) { ``return` `((2 * i) + 1); }``        ``int` `right(``int` `i) { ``return` `((2 * i) + 2); }``        ``public` `int` `getMin()``        ``{``            ``return` `harr[0];``        ``} ``// Returns minimum` `        ``// To replace root with new node x and heapify() new``        ``// root``        ``public` `void` `replaceMax(``int` `x)``        ``{``            ``this``.harr[0] = x;``            ``minHeapify(0);``        ``}` `        ``public` `MinHeap(``int``[] a, ``int` `size)``        ``{``            ``heap_size = size;``            ``harr = a; ``// store address of array``            ``int` `i = (heap_size - 1) / 2;``            ``while` `(i >= 0) {``                ``minHeapify(i);``                ``i--;``            ``}``        ``}` `        ``// Method to remove maximum element (or root) from``        ``// min heap``        ``public` `int` `extractMin()``        ``{``            ``if` `(heap_size == 0)``                ``return` `Int32.MaxValue;` `            ``// Store the maximum value.``            ``int` `root = harr[0];` `            ``// If there are more than 1 items, move the last``            ``// item to root and call heapify.``            ``if` `(heap_size > 1) {``                ``harr[0] = harr[heap_size - 1];``                ``minHeapify(0);``            ``}``            ``heap_size--;``            ``return` `root;``        ``}` `        ``// A recursive method to heapify a subtree with root``        ``// at given index This method assumes that the``        ``// subtrees are already heapified``        ``public` `void` `minHeapify(``int` `i)``        ``{``            ``int` `l = left(i);``            ``int` `r = right(i);``            ``int` `smallest = i;``            ``if` `(l < heap_size && harr[l] < harr[i])``                ``smallest = l;``            ``if` `(r < heap_size && harr[r] < harr[smallest])``                ``smallest = r;``            ``if` `(smallest != i) {``                ``int` `t = harr[i];``                ``harr[i] = harr[smallest];``                ``harr[smallest] = t;``                ``minHeapify(smallest);``            ``}``        ``}``    ``};` `    ``// Function to return k'th largest element in a given``    ``// array``    ``int` `kthSmallest(``int``[] arr, ``int` `N, ``int` `K)``    ``{` `        ``// Build a heap of first k elements: O(k) time``        ``MinHeap mh = ``new` `MinHeap(arr, N);` `        ``// Process remaining n-k elements. If current``        ``// element is smaller than root, replace root with``        ``// current element``        ``for` `(``int` `i = 0; i < K - 1; i++)``            ``mh.extractMin();` `        ``// Return root``        ``return` `mh.getMin();``    ``}` `    ``// Driver's code``    ``static` `public` `void` `Main()``    ``{``        ``int``[] arr = { 12, 3, 5, 7, 19 };``        ``int` `N = arr.Length, K = 2;``        ``GFG gfg = ``new` `GFG();` `        ``// Function call``        ``Console.Write(``"K'th smallest element is "``                      ``+ gfg.kthSmallest(arr, N, K));``    ``}``}` `// This code is contributed by rag2127`

## Javascript

 `// Javascript program to find K'th smallest element using min heap` `// class for Max Heap``class MinHeap {`  `    ``parent(i) {``        ``return` `(i - 1) / 2;``    ``};``    ``left(i) {``        ``return` `((2 * i) + 1);``    ``};``    ``right(i) {``        ``return` `((2 * i) + 2);``    ``}``    ``getMin() {``        ``return` `this``.harr[0];``    ``} ``// Returns minimum` `    ``// to replace root with new node x and heapify() new root``    ``replaceMax(x) {``        ``this``.harr[0] = x;``        ``minHeapify(0);``    ``}``    ``constructor(a, size) {``        ``this``.heap_size = size;``        ``this``.harr = a; ``// store address of array``        ``let i = (``this``.heap_size - 1) / 2;``        ``while` `(i >= 0) {``            ``this``.minHeapify(i);``            ``i--;``        ``}``    ``}` `    ``// Method to remove maximum element (or root) from min heap``    ``extractMin() {``        ``if` `(``this``.heap_size == 0)``            ``return` `Number.MAX_SAFE_INTEGER;` `        ``// Store the maximum value.``        ``let root = ``this``.harr[0];` `        ``// If there are more than 1 items, move the last item to root``        ``// and call heapify.``        ``if` `(``this``.heap_size > 1) {``            ``this``.harr[0] = ``this``.harr[``this``.heap_size - 1];``            ``this``.minHeapify(0);``        ``}``        ``this``.heap_size--;``        ``return` `root;``    ``}` `    ``// A recursive method to heapify a subtree with root at given index``    ``// This method assumes that the subtrees are already heapified``    ``minHeapify(i) {``        ``let l = ``this``.left(i);``        ``let r = ``this``.right(i);``        ``let smallest = i;``        ``if` `(l < ``this``.heap_size && ``this``.harr[l] < ``this``.harr[i])``            ``smallest = l;``        ``if` `(r < ``this``.heap_size && ``this``.harr[r] < ``this``.harr[smallest])``            ``smallest = r;``        ``if` `(smallest != i) {``            ``let t = ``this``.harr[i];``            ``this``.harr[i] = ``this``.harr[smallest];``            ``this``.harr[smallest] = t;``            ``this``.minHeapify(smallest);``        ``}``    ``}``};` `// Function to return k'th largest element in a given array``function` `kthSmallest(arr, N, K) {` `    ``// Build a heap of first k elements: O(k) time``    ``let mh = ``new` `MinHeap(arr, N);` `    ``// Process remaining N-K elements. If current element is``    ``// smaller than root, replace root with current element``    ``for` `(let i = 0; i < K - 1; i++)``        ``mh.extractMin();` `    ``// Return root``    ``return` `mh.getMin();``}` `// 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 gfgking.`

Output

`K'th smallest element is 5`

Time complexity: O(N + K Log N).
Auxiliary Space: O(N)

### K’th smallest element in an unsorted array using Max-Heap

Max-Heap can be used to find the kth smallest element, by inserting first K elements into Max-Heap and then compare remaining elements with the root of the Max-Heap and if the element is less than the root then remove the root and insert this element into the heap and finally return root of the Max-Heap

Follow the given steps to solve the problem:

• Build a Max-Heap MH of the first K elements (arr[0] to arr[K-1]) of the given array.
• For each element, after the Kth element (arr[K] to arr[n-1]), compare it with the root of MH.
• If the element is less than the root then make it the root and call heapify for Max-Heap MH
• b) Else ignore it.
• Finally, the root of the MH is the Kth smallest element.

Below is the Implementation of the above approach:

## C++

 `// C++ program to find k'th smallest element using max heap` `#include ``using` `namespace` `std;` `// Prototype of a utility function to swap two integers``void` `swap(``int``* x, ``int``* y);` `// A class for Max Heap``class` `MaxHeap {` `    ``int``* harr; ``// pointer to array of elements in heap``    ``int` `capacity; ``// maximum possible size of max heap``    ``int` `heap_size; ``// Current number of elements in max heap` `public``:``    ``MaxHeap(``int` `a[], ``int` `size); ``// Constructor``    ``void` `maxHeapify(``        ``int` `i); ``// To maxHeapify subtree rooted with index i``    ``int` `parent(``int` `i) { ``return` `(i - 1) / 2; }``    ``int` `left(``int` `i) { ``return` `(2 * i + 1); }``    ``int` `right(``int` `i) { ``return` `(2 * i + 2); }` `    ``int` `extractMax(); ``// extracts root (maximum) element``    ``int` `getMax() { ``return` `harr[0]; } ``// Returns maximum` `    ``// to replace root with new node x and heapify() new``    ``// root``    ``void` `replaceMax(``int` `x)``    ``{``        ``harr[0] = x;``        ``maxHeapify(0);``    ``}``};` `MaxHeap::MaxHeap(``int` `a[], ``int` `size)``{``    ``heap_size = size;``    ``harr = a; ``// store address of array``    ``int` `i = (heap_size - 1) / 2;``    ``while` `(i >= 0) {``        ``maxHeapify(i);``        ``i--;``    ``}``}` `// Method to remove maximum element (or root) from max heap``int` `MaxHeap::extractMax()``{``    ``if` `(heap_size == 0)``        ``return` `INT_MAX;` `    ``// Store the maximum value.``    ``int` `root = harr[0];` `    ``// If there are more than 1 items, move the last item to``    ``// root and call heapify.``    ``if` `(heap_size > 1) {``        ``harr[0] = harr[heap_size - 1];``        ``maxHeapify(0);``    ``}``    ``heap_size--;` `    ``return` `root;``}` `// A recursive method to heapify a subtree with root at``// given index This method assumes that the subtrees are``// already heapified``void` `MaxHeap::maxHeapify(``int` `i)``{``    ``int` `l = left(i);``    ``int` `r = right(i);``    ``int` `largest = i;` `    ``if` `(l < heap_size && harr[l] > harr[i])``        ``largest = l;` `    ``if` `(r < heap_size && harr[r] > harr[largest])``        ``largest = r;` `    ``if` `(largest != i) {``        ``swap(&harr[i], &harr[largest]);``        ``maxHeapify(largest);``    ``}``}` `// A utility function to swap two elements``void` `swap(``int``* x, ``int``* y)``{``    ``int` `temp = *x;``    ``*x = *y;``    ``*y = temp;``}` `// Function to return k'th largest element in a given array``int` `kthSmallest(``int` `arr[], ``int` `N, ``int` `K)``{``    ``// Build a heap of first k elements: O(k) time``    ``MaxHeap mh(arr, K);` `    ``// Process remaining n-k elements.  If current element``    ``// is smaller than root, replace root with current``    ``// element``    ``for` `(``int` `i = K; i < N; i++)``        ``if` `(arr[i] < mh.getMax())``            ``mh.replaceMax(arr[i]);` `    ``// Return root``    ``return` `mh.getMax();``}` `// Driver's code``int` `main()``{``    ``int` `arr[] = { 12, 3, 5, 7, 19 };``    ``int` `N = ``sizeof``(arr) / ``sizeof``(arr[0]), K = 4;` `    ``// Function call``    ``cout << ``"K'th smallest element is "``         ``<< kthSmallest(arr, N, K);``    ``return` `0;``}`

## Java

 `// A Java program to find k'th smallest element using max``// heap``import` `java.util.*;``class` `GFG {` `    ``// A class for Max Heap``    ``class` `MaxHeap {``        ``int``[] harr; ``// pointer to array of elements in heap``        ``int` `capacity; ``// maximum possible size of max heap``        ``int` `heap_size; ``// Current number of elements in max``                       ``// heap` `        ``int` `parent(``int` `i) { ``return` `(i - ``1``) / ``2``; }``        ``int` `left(``int` `i) { ``return` `(``2` `* i + ``1``); }``        ``int` `right(``int` `i) { ``return` `(``2` `* i + ``2``); }``        ``int` `getMax() { ``return` `harr[``0``]; } ``// Returns maximum` `        ``// to replace root with new node x and heapify() new``        ``// root``        ``void` `replaceMax(``int` `x)``        ``{``            ``this``.harr[``0``] = x;``            ``maxHeapify(``0``);``        ``}``        ``MaxHeap(``int` `a[], ``int` `size)``        ``{``            ``heap_size = size;``            ``harr = a; ``// store address of array``            ``int` `i = (heap_size - ``1``) / ``2``;``            ``while` `(i >= ``0``) {``                ``maxHeapify(i);``                ``i--;``            ``}``        ``}` `        ``// Method to remove maximum element (or root) from``        ``// max heap``        ``int` `extractMax()``        ``{``            ``if` `(heap_size == ``0``)``                ``return` `Integer.MAX_VALUE;` `            ``// Store the maximum value.``            ``int` `root = harr[``0``];` `            ``// If there are more than 1 items, move the last``            ``// item to root and call heapify.``            ``if` `(heap_size > ``1``) {``                ``harr[``0``] = harr[heap_size - ``1``];``                ``maxHeapify(``0``);``            ``}``            ``heap_size--;``            ``return` `root;``        ``}` `        ``// A recursive method to heapify a subtree with root``        ``// at given index This method assumes that the``        ``// subtrees are already heapified``        ``void` `maxHeapify(``int` `i)``        ``{``            ``int` `l = left(i);``            ``int` `r = right(i);``            ``int` `largest = i;``            ``if` `(l < heap_size && harr[l] > harr[i])``                ``largest = l;``            ``if` `(r < heap_size && harr[r] > harr[largest])``                ``largest = r;``            ``if` `(largest != i) {``                ``int` `t = harr[i];``                ``harr[i] = harr[largest];``                ``harr[largest] = t;``                ``maxHeapify(largest);``            ``}``        ``}``    ``};` `    ``// Function to return k'th largest element in a given``    ``// array``    ``int` `kthSmallest(``int` `arr[], ``int` `N, ``int` `K)``    ``{` `        ``// Build a heap of first k elements: O(k) time``        ``MaxHeap mh = ``new` `MaxHeap(arr, K);` `        ``// Process remaining n-k elements.  If current``        ``// element is smaller than root, replace root with``        ``// current element``        ``for` `(``int` `i = K; i < N; i++)``            ``if` `(arr[i] < mh.getMax())``                ``mh.replaceMax(arr[i]);` `        ``// Return root``        ``return` `mh.getMax();``    ``}` `    ``// Driver's code``    ``public` `static` `void` `main(String[] args)``    ``{``        ``int` `arr[] = { ``12``, ``3``, ``5``, ``7``, ``19` `};``        ``int` `N = arr.length, K = ``4``;``        ``GFG gfg = ``new` `GFG();` `        ``// Function call``        ``System.out.print(``"K'th smallest element is "``                         ``+ gfg.kthSmallest(arr, N, K));``    ``}``}` `// This code is contributed by Rajput-Ji`

## Python3

 `# Python3 program to find K'th smallest element``# using max heap` `# Class for Max Heap`  `class` `MaxHeap:``    ``# Constructor``    ``def` `__init__(``self``, a, size):``        ``# list of elements in the heap``        ``self``.harr ``=` `a``        ``# maximum possible size of max heap``        ``self``.capacity ``=` `None``        ``# current number of elements in max heap``        ``self``.heap_size ``=` `size` `        ``i ``=` `int``((``self``.heap_size ``-` `1``) ``/` `2``)``        ``while` `i >``=` `0``:``            ``self``.maxHeapify(i)``            ``i ``-``=` `1` `    ``def` `parent(``self``, i):``        ``return` `(i ``-` `1``) ``/` `2` `    ``def` `left(``self``, i):``        ``return` `2` `*` `i ``+` `1` `    ``def` `right(``self``, i):``        ``return` `2` `*` `i ``+` `2` `    ``# Returns maximum``    ``def` `getMax(``self``):``        ``return` `self``.harr[``0``]` `    ``# to replace root with new node x and heapify() new root``    ``def` `replaceMax(``self``, x):``        ``self``.harr[``0``] ``=` `x``        ``self``.maxHeapify(``0``)` `    ``# Method to remove maximum element (or root)``    ``# from max heap``    ``def` `extractMin(``self``):``        ``if` `self``.heap_size ``=``=` `0``:``            ``return` `float``(``"inf"``)` `        ``# Store the maximum value.``        ``root ``=` `self``.harr[``0``]` `        ``# If there are more than 1 items, move the``        ``# last item to root and call heapify``        ``if` `self``.heap_size > ``1``:``            ``self``.harr[``0``] ``=` `self``.harr[``self``.heap_size ``-` `1``]``            ``self``.maxHeapify(``0``)``        ``self``.heap_size ``-``=` `1``        ``return` `root` `    ``# A recursive method to heapify a subtree with root at``    ``# given index. This method assumes that the subtrees``    ``# are already heapified``    ``def` `maxHeapify(``self``, i):``        ``l ``=` `self``.left(i)``        ``r ``=` `self``.right(i)``        ``largest ``=` `i` `        ``if` `((l < ``self``.heap_size) ``and``                ``(``self``.harr[l] > ``self``.harr[i])):``            ``largest ``=` `l` `        ``if` `((r < ``self``.heap_size) ``and``                ``(``self``.harr[r] > ``self``.harr[largest])):``            ``largest ``=` `r` `        ``if` `largest !``=` `i:``            ``self``.harr[i], ``self``.harr[largest] ``=` `(``                ``self``.harr[largest], ``self``.harr[i])``            ``self``.maxHeapify(largest)`  `# Function to return k'th smallest element in a given array``def` `kthSmallest(arr, N, K):``    ``# Build a heap of first k elements in O(k) time``    ``mh ``=` `MaxHeap(arr, K)` `    ``# Process remaining n-k elements. If current element is``    ``# smaller than root, replace root with current element``    ``for` `i ``in` `range``(K, N):``        ``if` `arr[i] < mh.getMax():``            ``mh.replaceMax(arr[i])` `    ``# Return root``    ``return` `mh.getMax()`  `# Driver's code``if` `__name__ ``=``=` `'__main__'``:``    ``arr ``=` `[``12``, ``3``, ``5``, ``7``, ``19``]``    ``N ``=` `len``(arr)``    ``K ``=` `4` `    ``# Function call``    ``print``(``"K'th smallest element is"``, kthSmallest(arr, N, K))` `# Code contributed by Kevin Joshi`

## C#

 `// C# program to find k'th smallest element using max heap` `using` `System;` `public` `class` `GFG {` `    ``// A class for Max Heap``    ``public` `        ``class` `MaxHeap {``        ``public` `            ``int``[] harr; ``// pointer to array of elements in``                        ``// heap``        ``public` `            ``int` `capacity; ``// maximum possible size of max``                          ``// heap``        ``public` `            ``int` `heap_size; ``// Current number of elements in``                           ``// max heap` `        ``public` `            ``int``            ``parent(``int` `i)``        ``{``            ``return` `(i - 1) / 2;``        ``}``        ``public` `            ``int``            ``left(``int` `i)``        ``{``            ``return` `(2 * i + 1);``        ``}``        ``public` `            ``int``            ``right(``int` `i)``        ``{``            ``return` `(2 * i + 2);``        ``}``        ``public` `            ``int``            ``getMax()``        ``{``            ``return` `harr[0];``        ``} ``// Returns maximum` `        ``// to replace root with new node x and heapify() new``        ``// root``        ``public` `            ``void``            ``replaceMax(``int` `x)``        ``{``            ``this``.harr[0] = x;``            ``maxHeapify(0);``        ``}``        ``public` `            ``MaxHeap(``int``[] a, ``int` `size)``        ``{``            ``heap_size = size;``            ``harr = a; ``// store address of array``            ``int` `i = (heap_size - 1) / 2;``            ``while` `(i >= 0) {``                ``maxHeapify(i);``                ``i--;``            ``}``        ``}` `        ``// Method to remove maximum element (or root) from``        ``// max heap``        ``public` `            ``int``            ``extractMax()``        ``{``            ``if` `(heap_size == 0)``                ``return` `int``.MaxValue;` `            ``// Store the maximum value.``            ``int` `root = harr[0];` `            ``// If there are more than 1 items, move the last``            ``// item to root and call heapify.``            ``if` `(heap_size > 1) {``                ``harr[0] = harr[heap_size - 1];``                ``maxHeapify(0);``            ``}``            ``heap_size--;``            ``return` `root;``        ``}` `        ``// A recursive method to heapify a subtree with root``        ``// at given index This method assumes that the``        ``// subtrees are already heapified``        ``public` `            ``void``            ``maxHeapify(``int` `i)``        ``{``            ``int` `l = left(i);``            ``int` `r = right(i);``            ``int` `largest = i;` `            ``if` `(l < heap_size && harr[l] > harr[i])``                ``largest = l;` `            ``if` `(r < heap_size && harr[r] > harr[largest])``                ``largest = r;` `            ``if` `(largest != i) {``                ``int` `t = harr[i];``                ``harr[i] = harr[largest];``                ``harr[largest] = t;``                ``maxHeapify(largest);``            ``}``        ``}``    ``};` `    ``// Function to return k'th largest element in a given``    ``// array``    ``int` `kthSmallest(``int``[] arr, ``int` `N, ``int` `K)``    ``{` `        ``// Build a heap of first k elements: O(k) time``        ``MaxHeap mh = ``new` `MaxHeap(arr, K);` `        ``// Process remaining n-k elements.  If current``        ``// element is smaller than root, replace root with``        ``// current element``        ``for` `(``int` `i = K; i < N; i++)``            ``if` `(arr[i] < mh.getMax())``                ``mh.replaceMax(arr[i]);` `        ``// Return root``        ``return` `mh.getMax();``    ``}` `    ``// Driver's code``    ``public` `static` `void` `Main(String[] args)``    ``{``        ``int``[] arr = { 12, 3, 5, 7, 19 };``        ``int` `N = arr.Length, K = 4;``        ``GFG gfg = ``new` `GFG();` `        ``// Function call``        ``Console.Write(``"K'th smallest element is "``                      ``+ gfg.kthSmallest(arr, N, K));``    ``}``}` `// This code is contributed by gauravrajput1`

Output

`K'th smallest element is 12`

Time Complexity: O(K + (N-K) * Log K)
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 ``#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;``}`

## 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;``}`

## 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
Auxiliary Space: O(1)

## K’th smallest element in an unsorted array using Map:

This approach is very much similar to the QuickSelect and counting sort algorithm but much easier to implement. Use a map and then map each element with its frequency. And as an ordered map would store the data in a sorted manner, so keep on adding the frequency of each element till it does not become greater than or equal to k so that the k’th element from the start can be reached i.e. the k’th smallest element.

Example: A[] = {7, 0, 25, 6, 16, 17, 0}, K = 3

Follow the given steps to solve the problem:

• Store frequency of every element in a Map mp
• Now traverse over sorted elements in the Map mp and add their frequencies in a variable freq
• If at any point the value of freq is greater than or equal to K, then return the value of iterator of Map mp

Below is the Implementation of the above approach:

## C++

 `// C++ program for the above approach` `#include ``using` `namespace` `std;` `int` `Kth_smallest(map<``int``, ``int``> mp, ``int` `K)``{``    ``int` `freq = 0;``    ``for` `(``auto` `it = mp.begin(); it != mp.end(); it++) {``        ``freq += (it->second); ``// adding the frequencies of``                              ``// each element` `        ``if` `(freq >= K) ``// if at any point frequency becomes``                       ``// greater than or equal to k then``                       ``// return that element``        ``{``            ``return` `it->first;``        ``}``    ``}` `    ``return` `-1; ``// returning -1 if k>size of the array which``               ``// is an impossible scenario``}` `// Driver's code``int` `main()``{``    ``int` `N = 5;``    ``int` `K = 2;``    ``vector<``int``> arr = { 12, 3, 5, 7, 19 };` `    ``map<``int``, ``int``> mp;``    ``for` `(``int` `i = 0; i < N; i++) {``        ``mp[arr[i]] += 1; ``// mapping every element with it's``                         ``// frequency``    ``}` `    ``// Function call``    ``int` `ans = Kth_smallest(mp, K);``    ``cout << ``"The "` `<< K << ``"th smallest element is "` `<< ans``         ``<< endl;` `    ``return` `0;``}`

## Java

 `// Java program for the above approach` `import` `java.util.*;` `class` `GFG {``    ``static` `int` `Kth_smallest(TreeMap mp,``                            ``int` `K)``    ``{``        ``int` `freq = ``0``;``        ``for` `(Map.Entry it : mp.entrySet()) {` `            ``// adding the frequencies of each element``            ``freq += (``int``)it.getValue();` `            ``// if at any point frequency becomes``            ``// greater than or equal to k then``            ``// return that element``            ``if` `(freq >= K) {``                ``return` `(``int``)it.getKey();``            ``}``        ``}` `        ``return` `-``1``; ``// returning -1 if k>size of the array``                   ``// which is an impossible scenario``    ``}` `    ``// Driver's code``    ``public` `static` `void` `main(String[] args)``    ``{``        ``int` `N = ``5``;``        ``int` `K = ``2``;``        ``int``[] arr = { ``12``, ``3``, ``5``, ``7``, ``19` `};``        ``TreeMap mp = ``new` `TreeMap<>();` `        ``for` `(``int` `i = ``0``; i < N; i++) {` `            ``// mapping every element with``            ``// it's``            ``// frequency``            ``mp.put(arr[i], mp.getOrDefault(arr[i], ``0``) + ``1``);``        ``}` `        ``// Function call``        ``int` `ans = Kth_smallest(mp, K);` `        ``System.out.println(``            ``"The "` `+ K + ``"th smallest element is "` `+ ans);``    ``}``}` `// This code is contributed by harshit17.`

## Python3

 `# Python3 program for the above approach`  `def` `Kth_smallest(mp, K):` `    ``freq ``=` `0``    ``for` `it ``in` `sorted``(mp.keys()):``        ``freq ``+``=` `mp[it]  ``# adding the frequencies of``        ``# each element``        ``if` `freq >``=` `K:  ``# if at any point frequency becomes``            ``return` `it   ``# greater than or equal to k then``            ``# return that element``    ``return` `-``1`  `# returning -1 if k>size of the array which``    ``# is an impossible scenario`  `# driver's code``if` `__name__ ``=``=` `"__main__"``:``    ``N ``=` `5``    ``K ``=` `2``    ``arr ``=` `[``12``, ``3``, ``5``, ``7``, ``19``]``    ``mp ``=` `{}``    ``for` `i ``in` `range``(N):``        ``if` `arr[i] ``in` `mp:    ``# mapping every element with it's``            ``mp[arr[i]] ``=` `mp[arr[i]] ``+` `1`  `# frequency``        ``else``:``            ``mp[arr[i]] ``=` `1` `    ``# Function call``    ``ans ``=` `Kth_smallest(mp, K)``    ``print``(``"The "``, K, ``"th smallest element is "``, ans)` `# This code is contributed by Abhijeet Kumar(abhijeet19403)`

## C#

 `// C# program for the above approach` `using` `System;``using` `System.Collections;``using` `System.Collections.Generic;` `public` `class` `GFG {``    ``static` `int` `Kth_smallest(SortedDictionary<``int``, ``int``> mp,``                            ``int` `K)``    ``{``        ``int` `freq = 0;``        ``foreach``(``var` `it ``in` `mp)``        ``{` `            ``// Adding the frequencies of each element``            ``freq += (``int``)it.Value;` `            ``// If at any point frequency becomes``            ``// greater than or equal to k then``            ``// return that element``            ``if` `(freq >= K) {``                ``return` `(``int``)it.Key;``            ``}``        ``}` `        ``return` `-1; ``// returning -1 if K > size of the array``                   ``// which is an impossible scenario``    ``}` `    ``// Driver's code``    ``public` `static` `void` `Main(String[] args)``    ``{``        ``int` `N = 5;``        ``int` `K = 2;``        ``int``[] arr = { 12, 3, 5, 7, 19 };` `        ``SortedDictionary<``int``, ``int``> mp``            ``= ``new` `SortedDictionary<``int``, ``int``>();``        ``for` `(``int` `i = 0; i < N; i++) {` `            ``// mapping every element with``            ``// it's frequency``            ``mp.Add(arr[i], mp.ContainsKey(arr[i])``                               ``? mp[arr[i]] + 1``                               ``: 1);``        ``}` `        ``// Function call``        ``int` `ans = Kth_smallest(mp, K);` `        ``Console.WriteLine(``            ``"The "` `+ K + ``"th smallest element is "` `+ ans);``    ``}``}` `// This code is contributed by Abhijeet Kumar(abhijeet19403)`

## Javascript

 `// Javascript program to implement the approach``      ``//Function for creating Map``      ``function` `crateMap(arr, N) {``        ``var` `brr = arr.sort(``function` `(a, b) {``          ``return` `a - b;``        ``});` `        ``let mp = {};``        ``for` `(``var` `i = 0; i < N; i++) {``          ``mp[brr[i]] = 0;``        ``}` `        ``for` `(``var` `i = 0; i < N; i++) {``          ``mp[brr[i]] += 1;``        ``}``        ``return` `mp;``      ``}` `      ``//Function for finding kth Smallest``      ``function` `Kth_smallest(mp, K) {``        ``var` `freq = 0;``        ``for` `(const key ``in` `mp) {``          ``freq += mp[key]; ``// adding the frequencies of each element` `          ``if` `(freq >= K) {``            ``// if at any point frequency becomes``            ``// greater than or equal to k then``            ``// return that element``            ``return` `key;``          ``}``        ``}` `        ``return` `-1; ``// returning -1 if k>size of the array which``        ``// is an impossible scenario``      ``}` `      ``var` `N = 5;``      ``var` `K = 2;``      ``var` `arr = [12, 3, 5, 7, 19];``      ``let mpp = crateMap(arr, N);` `      ``// Function call``      ``var` `ans = Kth_smallest(mpp, K);``      ``console.log(``"The "` `+ K + ``"th smallest element is "` `+ ans);`

Output

```The 2th smallest element is 5
```

Time Complexity: O(N log N)
Auxiliary Space: O(N)

## K’th smallest element in an unsorted array using Priority Queue:

To find the Kth minimum element in an array, insert the elements into the priority queue until the size of it is less than K, and then compare remaining elements with the root of the priority queue and if the element is less than the root then remove the root and insert this element into the priority queue and finally return root of the priority queue

Follow the given steps to solve the problem:

• Build a priority queue of the first K elements (arr[0] to arr[K-1]) of the given array.
• For each element, after the Kth element (arr[K] to arr[n-1]), compare it with the root of priority queue.
• If the element is less than the root then remove the root and insert this element into the priority queue
• b) Else ignore it.
• Finally, the root of the priority queue is the Kth smallest element.

Below is the Implementation of the above approach:

## C++

 `// C++ code to implement the approach``#include ``using` `namespace` `std;` `// Function to find the kth smallest array element``int` `kthSmallest(``int` `arr[], ``int` `N, ``int` `K)``{` `    ``// For finding min element we need (Max heap)priority``    ``// queue``    ``priority_queue<``int``> pq;` `    ``for` `(``int` `i = 0; i < K; i++) {``        ``// First push first K elements into heap``        ``pq.push(arr[i]);``    ``}``    ``// Now check from k to last element``    ``for` `(``int` `i = K; i < N; i++) {` `        ``// If current element is < top that means``        ``// there are  other k-1 lesser elements``        ``// are present at bottom thus, pop that element``        ``// and add kth largest element into the heap till``        ``// curr at last all the greater element than kth``        ``// element will get pop off and at the top of heap``        ``// there will be kth smallest element``        ``if` `(arr[i] < pq.top()) {``            ``pq.pop();``            ``// Push curr element``            ``pq.push(arr[i]);``        ``}``    ``}` `    ``// Return top of element``    ``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

 `// Java code to implement the approach` `import` `java.util.*;` `// Custom comparator class to form the Max heap``class` `MinHeapComparator ``implements` `Comparator {` `    ``@Override``    ``public` `int` `compare(Integer number1, Integer number2)``    ``{``        ``int` `value = number1.compareTo(number2);` `        ``// Elements are sorted in reverse order``        ``if` `(value > ``0``) {``            ``return` `-``1``;``        ``}``        ``else` `if` `(value < ``0``) {``            ``return` `1``;``        ``}``        ``else` `{``            ``return` `0``;``        ``}``    ``}``}``class` `GFG {` `    ``// Function to find kth smallest array element``    ``static` `int` `kthSmallest(``int``[] v, ``int` `N, ``int` `K)``    ``{``        ``// For finding min element we need (Max``        ``// heap)priority queue``        ``PriorityQueue heap1``            ``= ``new` `PriorityQueue(``                ``new` `MinHeapComparator());` `        ``for` `(``int` `i = ``0``; i < N; ++i) {` `            ``// Insert elements into``            ``// the priority queue``            ``heap1.add(v[i]);` `            ``// If current element is less than top, that``            ``// means there are other k-1 lesser elements are``            ``// present at bottom``            ``// thus pop that element and add kth largest``            ``// element into the heap till curr at last all``            ``// the greater element than kth element will get``            ``// pop off and at the top of heap there will be``            ``// kth smallest element``            ``if` `(heap1.size() > K) {``                ``heap1.remove();``            ``}``        ``}` `        ``// Return the top of the heap as kth smallest``        ``// element``        ``return` `heap1.peek();``    ``}` `    ``// Driver's code``    ``public` `static` `void` `main(String[] args)``    ``{``        ``// Given array``        ``int``[] vec``            ``= { ``10``, ``5``, ``4``, ``3``, ``48``, ``15``, ``6``, ``2``, ``33``, ``53``, ``10` `};` `        ``// Size of array``        ``int` `N = vec.length;` `        ``// Given K``        ``int` `K = ``4``;` `        ``// Function Call``        ``System.out.println(``"Kth Smallest Element: "``                           ``+ kthSmallest(vec, N, K));``    ``}``}`

## Python3

 `# Python3 code to implement the approach``import` `heapq` `# Function to find the kth smallest array element`  `def` `kthSmallest(arr, N, K):` `    ``# For finding min element we need (Max heap)priority queue``    ``pq ``=` `[]``    ``for` `i ``in` `range``(K):` `        ``# First push first K elements into heap``        ``heapq.heappush(pq, arr[i])``        ``heapq._heapify_max(pq)` `    ``# Now check from k to last element``    ``for` `i ``in` `range``(K, N):` `        ``# If current element is < first that means``        ``# there are  other k-1 lesser elements``        ``# are present at bottom thus, pop that element``        ``# and add kth largest element into the heap till curr``        ``# at last all the greater element than kth element will get pop off``        ``# and at the top of heap there will be kth smallest element``        ``if` `arr[i] < pq[``0``]:``            ``heapq.heappop(pq)` `            ``# Push curr element``            ``heapq.heappush(pq, arr[i])``            ``heapq._heapify_max(pq)``    ``# Return first of element``    ``return` `pq[``0``]`  `# Driver's code:``if` `__name__ ``=``=` `"__main__"``:``    ``N ``=` `10``    ``arr ``=` `[``10``, ``5``, ``4``, ``3``, ``48``, ``6``, ``2``, ``33``, ``53``, ``10``]``    ``K ``=` `4` `    ``# Function call``    ``print``(``"Kth Smallest Element is:"``, kthSmallest(arr, N, K))`  `# This code is contributed by Tapesh(tapeshdua420)`

## C#

 `// C# program to implement``// the above approach` `using` `System;``using` `System.Collections.Generic;` `class` `GFG {` `    ``// Function to find the kth smallest array element``    ``static` `int` `kthSmallest(``int``[] arr, ``int` `N, ``int` `K)``    ``{` `        ``// For finding min element we need (Max``        ``// heap)priority queue``        ``List<``int``> pq = ``new` `List<``int``>();` `        ``for` `(``int` `i = 0; i < K; i++) {` `            ``// First push first K elements into heap``            ``pq.Add(arr[i]);``        ``}``        ``// Now check from k to last element``        ``for` `(``int` `i = K; i < N; i++) {` `            ``// If current element is < top that means``            ``// there are  other k-1 lesser elements``            ``// are present at bottom thus, pop that element``            ``// and add kth largest element into the heap``            ``// till curr at last all the greater element``            ``// than kth element will get pop off and at the``            ``// top of heap there will be kth smallest``            ``// element``            ``if` `(arr[i] < pq[0]) {``                ``pq.Sort();``                ``pq.Reverse();` `                ``pq.RemoveAt(0);``                ``// Push curr element``                ``pq.Add(arr[i]);``            ``}``        ``}` `        ``// Return top of element``        ``return` `pq[0];``    ``}` `    ``// Driver's Code``    ``public` `static` `void` `Main()``    ``{``        ``// Given array``        ``int``[] vec``            ``= { 10, 5, 4, 3, 48, 15, 6, 2, 33, 53, 10 };` `        ``// Size of array``        ``int` `N = vec.Length;` `        ``// Given K``        ``int` `K = 4;` `        ``// Function Call``        ``Console.WriteLine(``"Kth Smallest Element: "``                          ``+ kthSmallest(vec, N, K));``    ``}``}` `// This code is contributed by sanjoy_62.`

Output

`Kth Smallest Element is: 5`

Time complexity: O(K log K +  (N – K) log K)
Auxiliary Space: O(K)

## K’th smallest element in an unsorted array using Binary Search:

The idea to solve this problem is that the Kth smallest element would be the element at the kth position if the array was sorted in increasing order. Using this logic, binary search can be used to predict the index of an element as if the array was sorted but without actually sorting the array.

Follow the given steps to solve the problem:

• Find low and high that is the range where our answer can lie.
• Apply Binary Search on this range.
• If the selected element which would be 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 which would be the answer.

Below is the implementation of the 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.
Auxiliary Space: O(1)

Next:

My Personal Notes arrow_drop_up