Skip to content

Commit f6dfcf3

Browse files
authored
quick select algorithm
Initial File
1 parent e05cafc commit f6dfcf3

1 file changed

Lines changed: 38 additions & 0 deletions

File tree

quick select

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
def swap(A, i, j):
2+
temp = A[i]
3+
A[i] = A[j]
4+
A[j] = temp
5+
6+
def partition(A, left, right, pIndex):
7+
pivot = A[pIndex]
8+
i = left - 1
9+
for j in range(left, right):
10+
if A[j] <= pivot:
11+
i = i+1
12+
swap(A, i, j)
13+
swap(A, i+1, pIndex)
14+
return i+1
15+
16+
def quickSelect(A, left, right, k):
17+
# If the list contains only one element, return that element
18+
if left == right:
19+
return A[left]
20+
# select a pIndex between left and right
21+
pIndex = right
22+
pIndex = partition(A, left, right, pIndex)
23+
# The pivot is in its sorted position
24+
if k == pIndex:
25+
return A[k]
26+
# if k is less than the pivot index
27+
elif k < pIndex:
28+
return quickSelect(A, left, pIndex - 1, k)
29+
# if k is more than the pivot index
30+
else:
31+
return quickSelect(A, pIndex + 1, right, k)
32+
33+
if __name__ == '__main__':
34+
35+
A = [7, 4, 6, 3, 9, 1]
36+
k = 3
37+
38+
print("Kth smallest element is", quickSelect(A, 0, len(A)-1, k-1))

0 commit comments

Comments
 (0)