QuickSelect ( A Simple Iterative Implementation ) | C # program for iterative implementation of QuickSelect ; Standard Lomuto partition function ; Implementation of QuickSelect ; Partition a [ left . . right ] around a pivot and find the position of the pivot ; If pivot itself is the k - th smallest element ; If there are more than k - 1 elements on left of pivot , then k - th smallest must be on left side . ; Else k - th smallest is on right side . ; Driver Code
using System ; class GFG { static int partition ( int [ ] arr , int low , int high ) { int temp ; int pivot = arr [ high ] ; int i = ( low - 1 ) ; for ( int j = low ; j <= high - 1 ; j ++ ) { if ( arr [ j ] <= pivot ) { i ++ ; temp = arr [ i ] ; arr [ i ] = arr [ j ] ; arr [ j ] = temp ; } } temp = arr [ i + 1 ] ; arr [ i + 1 ] = arr [ high ] ; arr [ high ] = temp ; return ( i + 1 ) ; } static int kthSmallest ( int [ ] a , int left , int right , int k ) { while ( left <= right ) { int pivotIndex = partition ( a , left , right ) ; if ( pivotIndex == k - 1 ) return a [ pivotIndex ] ; else if ( pivotIndex > k - 1 ) right = pivotIndex - 1 ; else left = pivotIndex + 1 ; } return - 1 ; } public static void Main ( String [ ] args ) { int [ ] arr = { 10 , 4 , 5 , 8 , 11 , 6 , 26 } ; int n = arr . Length ; int k = 5 ; Console . WriteLine ( " K - th ▁ smallest ▁ element ▁ is ▁ " + kthSmallest ( arr , 0 , n - 1 , k ) ) ; } }