Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import random
- def quickselect(arr, k):
- """
- Returns the k-th smallest element of list within arr.
- """
- if len(arr) == 1:
- return arr[0]
- pivot = random.choice(arr)
- lows = [el for el in arr if el < pivot]
- highs = [el for el in arr if el > pivot]
- pivots = [el for el in arr if el == pivot]
- if k < len(lows):
- return quickselect(lows, k)
- elif k < len(lows) + len(pivots):
- return pivots[0]
- else:
- return quickselect(highs, k - len(lows) - len(pivots))
- # Example usage:
- arr = [3, 2, 1, 5, 4]
- k = 2 # looking for the 3rd smallest element, index 2
- print(quickselect(arr, k)) # Output: 3
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement