-
Notifications
You must be signed in to change notification settings - Fork 464
Expand file tree
/
Copy pathQuick_Select.py
More file actions
25 lines (24 loc) · 804 Bytes
/
Quick_Select.py
File metadata and controls
25 lines (24 loc) · 804 Bytes
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
def quickselect(array, k):
position = k - 1
return quickSelectHelper(array, 0, len(array) - 1, position)
def quickSelectHelper(array, srtIdx, endIdx, position):
while True:
if srtIdx > endIdx:
raise Exception("Algorrithm should never be here!")
pivotIdx = srtIdx
leftIdx = srtIdx + 1
rightIdx = endIdx
while leftIdx <= rightIdx:
if array[leftIdx] > array[pivotIdx] > array[rightIdx]:
array[leftIdx], array[rightIdx] = array[rightIdx], array[leftIdx]
if array[leftIdx] <= array[pivotIdx]:
leftIdx += 1
if array[rightIdx] >= array[pivotIdx]:
rightIdx -= 1
array[pivotIdx], array[rightIdx] = array[rightIdx], array[pivotIdx]
if rightIdx == position:
return array[position]
elif rightIdx > position:
endIdx = rightIdx - 1
else:
srtIdx = rightIdx + 1