human
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"
How can the above be solved in Python?
assistant
#Here is code to quickSelect ( A Simple Iterative Implementation ) and the other steps required.
 def partition ( arr , low , high ) :
	pivot = arr [ high ]
	i = ( low - 1 )
	for j in range ( low , high ) :
		if arr [ j ] <= pivot :
			i += 1
			arr [ i ] , arr [ j ] = arr [ j ] , arr [ i ]
	arr [ i + 1 ] , arr [ high ] = arr [ high ] , arr [ i + 1 ]
	return ( i + 1 )
def kthSmallest ( a , left , right , k ) :
	while left <= right :
		pivotIndex = partition ( a , left , right )
		if pivotIndex == k - 1 :
			return a [ pivotIndex ]
		elif pivotIndex > k - 1 :
			right = pivotIndex - 1
		else :
			left = pivotIndex + 1
	return - 1
arr = [ 10 , 4 , 5 , 8 , 11 , 6 , 26 ]
n = len ( arr )
k = 5
print ( " K - th ▁ smallest ▁ element ▁ is " , kthSmallest ( arr , 0 , n - 1 , k ) )