Algorithm Steps
- Given an array of numbers and an integer
k
(1-indexed), the goal is to find the kth smallest element. - If the array contains only one element, return that element.
- Randomly choose a pivot from the array.
- Partition the array into three groups:
lows
(elements less than the pivot),pivots
(elements equal to the pivot), andhighs
(elements greater than the pivot). - If
k
is less than or equal to the size oflows
, recursively search inlows
. - If
k
is within the size oflows
pluspivots
, the pivot is the kth smallest element. - Otherwise, recursively search in
highs
with an updatedk
(subtracting the sizes oflows
andpivots
).
Quickselect Algorithm Program in Different Programming Languages Code
Python
Java
JavaScript
C
C++
C#
Kotlin
Swift
Go
Php
import random
def quickselect(arr, k):
if len(arr) == 1:
return arr[0]
pivot = random.choice(arr)
lows = [x for x in arr if x < pivot]
highs = [x for x in arr if x > pivot]
pivots = [x for x in arr if x == pivot]
if k <= len(lows):
return quickselect(lows, k)
elif k <= len(lows) + len(pivots):
return pivot
else:
return quickselect(highs, k - len(lows) - len(pivots))
if __name__ == '__main__':
arr = [7, 10, 4, 3, 20, 15]
k = 3
print("The", k, "th smallest element is:", quickselect(arr, k))