QuickSelect ( A Simple Iterative Implementation ) | 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
function partition ( arr , low , high ) { let temp ; let pivot = arr [ high ] ; let i = ( low - 1 ) ; for ( let 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 ) ; } function kthSmallest ( a , left , right , k ) { while ( left <= right ) { let 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 ; } let arr = [ 10 , 4 , 5 , 8 , 11 , 6 , 26 ] ; let n = arr . length ; let k = 5 ; document . write ( " " + kthSmallest ( arr , 0 , n - 1 , k ) ) ;