Skip to content

Commit 3df438b

Browse files
committed
QuickSelect.py finally approved
1 parent 25566f6 commit 3df438b

1 file changed

Lines changed: 38 additions & 0 deletions

File tree

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
#Finding Kth smallest value in list by selection algorithms
2+
3+
def quick_select(array_list, start, end, k):
4+
split = partition(array_list, start, end)
5+
if split == k:
6+
return array_list[split]
7+
elif split < k:
8+
return quick_select(array_list, split + 1, end, k)
9+
else:
10+
return quick_select(array_list, start, split - 1, k)
11+
12+
13+
def partition(unsorted_array, first_index, last_index):
14+
pivot = unsorted_array[first_index]
15+
pivot_index = first_index
16+
index_of_last_element = last_index
17+
less_than_pivot_index = index_of_last_element
18+
greater_than_pivot_index = first_index + 1
19+
while True:
20+
while unsorted_array[greater_than_pivot_index] < pivot and greater_than_pivot_index < last_index:
21+
greater_than_pivot_index += 1
22+
while unsorted_array[less_than_pivot_index] > pivot and less_than_pivot_index >= first_index:
23+
less_than_pivot_index -= 1
24+
if greater_than_pivot_index < less_than_pivot_index:
25+
temp = unsorted_array[greater_than_pivot_index]
26+
unsorted_array[greater_than_pivot_index] = unsorted_array[less_than_pivot_index]
27+
unsorted_array[less_than_pivot_index] = temp
28+
else:
29+
break
30+
unsorted_array[pivot_index] = unsorted_array[less_than_pivot_index]
31+
unsorted_array[less_than_pivot_index] = pivot
32+
return less_than_pivot_index
33+
34+
35+
list1 = [3,1,10, 4, 6, 5]
36+
print("The 2nd smallest element is", quick_select(list1, 0, 5, 1))
37+
print("The 3rd smallest element is", quick_select(list1, 0, 5, 2))
38+

0 commit comments

Comments
 (0)