-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathquick_select.py
49 lines (39 loc) · 1.44 KB
/
quick_select.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import random
import colorama
from colorama import Fore
colorama.init(autoreset=True)
def quick_select(arr, k):
"""
Finds the k-th smallest element in an unsorted array using the Quick Select algorithm.
:param arr: List of numbers
:param k: Position (1-indexed) of the element to find
:return: k-th smallest element
:raises ValueError: If k is out of bounds
"""
# Input validation
if not isinstance(arr, list) or len(arr) == 0:
raise ValueError("Input must be a non-empty list.")
if not (1 <= k <= len(arr)):
raise ValueError("k must be between 1 and the length of the array.")
if len(arr) == 1:
return arr[0]
# Choose a random pivot
pivot = random.choice(arr)
# Partitioning the array into three parts
left = [x for x in arr if x < pivot]
mid = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
# Recursive selection based on the size of left partition
if k <= len(left):
return quick_select(left, k)
elif k <= len(left) + len(mid):
return pivot
else:
return quick_select(right, k - len(left) - len(mid))
if __name__ == "__main__":
# Example usage
numbers = [12, 4, 19, 33, 7, 1, 25, 18]
k = 3 # Looking for the 3rd smallest element
print(Fore.GREEN + "Array of numbers:", numbers)
kth_element = quick_select(numbers, k)
print(Fore.YELLOW + f"{k}-rd smallest element: {kth_element}")