Skip to content

Commit d19915e

Browse files
committed
Added Python Implementation of QuickSelect
1 parent cafbe77 commit d19915e

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
#!/usr/bin/env python3
2+
3+
'''
4+
Python Implementation of Quick Select
5+
input : array of values, n (index @ which value is required)
6+
output : Value of element at nth index of array
7+
'''
8+
9+
10+
def QuickSelect(arr, n):
11+
print(arr, n)
12+
pivot = arr[0]
13+
left = [x for x in arr[1:] if x < pivot]
14+
right = [x for x in arr[1:] if x >= pivot]
15+
16+
index_of_pivot = len(left)
17+
18+
if n < index_of_pivot:
19+
return QuickSelect(left, n)
20+
elif n > index_of_pivot:
21+
return QuickSelect(right, n - index_of_pivot - 1)
22+
else:
23+
return pivot
24+
25+
26+
def run_tests():
27+
array, index = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1], 3
28+
print(bool(QuickSelect(array, index), sorted(array)[index] ))
29+
30+
array, index = [0, 8, 7, 5, 2, 3, 5], 5
31+
print(bool(QuickSelect(array, index), sorted(array)[index] ))
32+
33+
array, index = [36, 8, 7, 5, 2, 3, 5], 5
34+
print(bool( QuickSelect(array, index), sorted(array)[index] ))

0 commit comments

Comments
 (0)