K’th Smallest/Largest Element in Unsorted Array | Set 1

• Difficulty Level : Medium
• Last Updated : 10 Jan, 2022

Given an array and a number k where k is smaller than the size of the array, we need to find the k’th smallest element in the given array. It is 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

Recommended: Please solve it on “PRACTICE” first, before moving on to the solution.

Method 1 (Simple Solution)
A simple solution is to sort the given array using an O(N log N) sorting algorithm like Merge Sort, Heap Sort, etc, and return the element at index k-1 in the sorted array.
Time Complexity of this solution is O(N Log N)

C++

 // Simple C++ program to find k'th smallest element #include #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 program to test above methods int main() {     int arr[] = { 12, 3, 5, 7, 19 };     int n = sizeof(arr) / sizeof(arr), k = 2;     cout << "K'th smallest element is " << kthSmallest(arr, n, k);     return 0; }

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 program     public static void main(String[] args)     {         Integer arr[] = new Integer[] { 12, 3, 5, 7, 19 };         int k = 2;         System.out.print("K'th smallest element is " + kthSmallest(arr, k));     } }   // 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     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 program     public static void Main()     {         int[] arr = new int[] { 12, 3, 5,                                 7, 19 };         int k = 2;         Console.Write("K'th smallest element"                       + " is " + kthSmallest(arr, k));     } }   // This code is contributed by nitin mittal.



Javascript



Output

K'th smallest element is 5

Method 2 (using set from C++ STL)

we can find the kth smallest element in time complexity better than O(N log N). we know the Set in C++ STL is implemented using Binary Search Tree and we also know that the time complexity of all cases(searching, inserting, deleting ) in BST is log (n) in the average case and O(n) in the worst case. We are using set because it is mentioned in the question that all the elements in an array are distinct.

The following is the C++ implementation of the above method.

C++

 /* the following code demonstrates how to find kth smallest element using set from C++ STL */   #include using namespace std;   int main() {       int arr[] = { 12, 3, 5, 7, 19 };     int n = sizeof(arr) / sizeof(arr);     int k = 4;       set s(arr, arr + n);     set::iterator itr         = s.begin(); // s.begin() returns a pointer to first                      // element in the set     advance(itr, k - 1); // itr points to kth element in set       cout << *itr << "\n";       return 0; }

Output

10

Time Complexity:  O( log N) in Average Case and O(N) in Worst Case
Auxiliary Space: O(N)

Method 3 (Using Min Heap – HeapSelect)
We can find k’th smallest element in time complexity better than O(N Log N). A simple optimization is to create a Min Heap of the given n elements and call extractMin() k times.

The following is C++ implementation of above method.

C++

 // A 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     void MinHeapify(int i); // To minheapify 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 extractMin(); // extracts root (minimum) element     int getMin() { return harr; } // 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;       // If there are more than 1 items, move the last item to root     // and call heapify.     if (heap_size > 1) {         harr = 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 program to test above methods int main() {     int arr[] = { 12, 3, 5, 7, 19 };     int n = sizeof(arr) / sizeof(arr), k = 2;     cout << "K'th smallest element is " << kthSmallest(arr, n, k);     return 0; }

Java

 // A Java program to find k'th smallest element using min heap import java.util.*; 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; } // Returns minimum       // to replace root with new node x and heapify() new root     void replaceMax(int x)     {       this.harr = 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;         // If there are more than 1 items, move the last item to root       // and call heapify.       if (heap_size > 1)       {         harr = 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 program to test above methods   public static void main(String[] args)   {     int arr[] = { 12, 3, 5, 7, 19 };     int n = arr.length, k = 2;     GFG gfg = new GFG();     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       # 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           # If there are more than 1 items, move the last item         # to root and call heapify         if self.heap_size > 1:             self.harr = 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 code arr = [12, 3, 5, 7, 19] n = len(arr) k = 2 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; } // Returns minimum       // to replace root with new node x and heapify() new root     public void replaceMax(int x)     {       this.harr = 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;         // If there are more than 1 items, move the last item to root       // and call heapify.       if (heap_size > 1)       {         harr = 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 program to test above methods   static public void Main (){     int[] arr = { 12, 3, 5, 7, 19 };     int n = arr.Length, k = 2;     GFG gfg = new GFG();     Console.Write("K'th smallest element is " +                   gfg.kthSmallest(arr, n, k));   } }   // This code is contributed by rag2127

Output

K'th smallest element is 5

Time complexity of this solution is O(n + kLogn).

Method 4 (Using Max-Heap)
We can also use Max Heap for finding the k’th smallest element. Following is an algorithm.
1) Build a Max-Heap MH of the first k elements (arr to arr[k-1]) of the given array. O(k)
2) For each element, after the k’th element (arr[k] to arr[n-1]), compare it with root of MH.
……a) If the element is less than the root then make it root and call heapify for MH
……b) Else ignore it.
// The step 2 is O((n-k)*logk)
3) Finally, the root of the MH is the kth smallest element.
Time complexity of this solution is O(k + (n-k)*Logk)

The following is C++ implementation of the above algorithm

C++

 // A C++ program to find k'th smallest element using max heap #include #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; } // Returns maximum       // to replace root with new node x and heapify() new root     void replaceMax(int x)     {         harr = 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;       // If there are more than 1 items, move the last item to root     // and call heapify.     if (heap_size > 1) {         harr = 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 program to test above methods int main() {     int arr[] = { 12, 3, 5, 7, 19 };     int n = sizeof(arr) / sizeof(arr), k = 4;     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; } // Returns maximum       // to replace root with new node x and heapify() new root     void replaceMax(int x)     {       this.harr = 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;         // If there are more than 1 items, move the last item to root       // and call heapify.       if (heap_size > 1)       {         harr = 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 program to test above methods   public static void main(String[] args)   {     int arr[] = { 12, 3, 5, 7, 19 };     int n = arr.length, k = 4;     GFG gfg = new GFG();     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       # to replace root with new node x and heapify() new root     def replaceMax(self, x):         self.harr = 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           # If there are more than 1 items, move the         # last item to root and call heapify         if self.heap_size > 1:             self.harr = 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 code arr = [12, 3, 5, 7, 19] n = len(arr) k = 4 print("K'th smallest element is", kthSmallest(arr, n, k))   # Code contributed by Kevin Joshi

C#

 // A 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;         } // Returns maximum           // to replace root with new node x and heapify() new         // root         public               void             replaceMax(int x)         {             this.harr = 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;               // If there are more than 1 items, move the last             // item to root and call heapify.             if (heap_size > 1) {                 harr = 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 code     public static void Main(String[] args)     {         int[] arr = { 12, 3, 5, 7, 19 };         int n = arr.Length, k = 4;         GFG gfg = new GFG();         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

Method 5 (QuickSelect)
This is an optimization over method 1 if QuickSort is used as a sorting algorithm in first step. In QuickSort, we 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. The worst case time complexity of this method is O(n2), but it works in O(n) on average.

C++

 #include #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 program to test above methods int main() {     int arr[] = { 12, 3, 5, 7, 4, 19, 26 };     int n = sizeof(arr) / sizeof(arr), k = 3;     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 program to test above methods     public static void main(String[] args)     {         Integer arr[] = new Integer[] { 12, 3, 5, 7, 4, 19, 26 };         int k = 3;         System.out.print("K'th smallest element is " + kthSmallest(arr, 0, arr.length - 1, k));     } }   // This code is contributed by Chhavi

Python3

 # 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 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 Code     public static void Main()     {         int[] arr = { 12, 3, 5, 7, 4, 19, 26 };         int k = 3;         Console.Write("K'th smallest element is " + kthSmallest(arr, 0, arr.Length - 1, k));     } }   // This code is contributed // by 29AjayKumar

Javascript



Output

K'th smallest element is 5

Method 6 (Map STL)

A map based STL approach is although very much similar to the quickselect and counting sort algorithm but much easier to implement. We can use an ordered map and map each element with its frequency. And as we know that an ordered map would store the data in a sorted manner, we keep on adding the frequency of each element till it does not become greater than or equal to k so that we reach the k’th element from the start i.e. the k’th smallest element.

Eg –

Array={7,0,25,6,16,17,0}

k=3 Now in order to get the k’th largest element, we need to add the frequencies till it becomes greater than or equal to 3. It is clear from the above that the frequency of 0 + frequency of 6 will become equal to 3 so the third smallest number in the array will be 6.

We can achieve the above using an iterator to traverse the map.

C++

 #include using namespace std; int Kth_smallest(map m, int k) {     int freq = 0;     for (auto it = m.begin(); it != m.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 } int main() {     int n = 5;     int k = 2;     vector arr = { 12, 3, 5, 7, 19 };     map m;     for (int i = 0; i < n; i++) {         m[arr[i]] += 1; // mapping every element with it's                         // frequency     }     int ans = Kth_smallest(m, k);     cout << "The " << k << "rd smallest element is " << ans          << endl;     return 0; }

Java

 // Java program for the above approach import java.util.*;   class GFG {     static int Kth_smallest(TreeMap m,                             int k)     {         int freq = 0;         for (Map.Entry it : m.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 code     public static void main(String[] args)     {         int n = 5;         int k = 2;         int[] arr = { 12, 3, 5, 7, 19 };         TreeMap m = new TreeMap<>();         for (int i = 0; i < n; i++) {             // mapping every element with             // it's             // frequency             m.put(arr[i], m.getOrDefault(arr[i], 0) + 1);         }         int ans = Kth_smallest(m, k);           System.out.println(             "The " + k + "rd smallest element is " + ans);     } }   // This code is contributed by rajsanghavi9.

Output

The 2rd smallest element is 5

There are two more solutions which are better than above discussed ones: One solution is to do randomized version of quickSelect() and other solution is the worst case linear time algorithm (see the following posts).
K’th Smallest/Largest Element in Unsorted Array | Set 2 (Expected Linear Time)
K’th Smallest/Largest Element in Unsorted Array | Set 3 (Worst Case Linear Time)

My Personal Notes arrow_drop_up
Recommended Articles
Page :