-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathQuicksort.py
36 lines (30 loc) · 986 Bytes
/
Quicksort.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
# Quicksort implementation
def quicksort(A, lo=0, hi=len(A)-1):
if lo < hi:
p = partition(A, lo, hi)
quicksort(A, lo, p-1)
quicksort(A, p+1, hi)
# Lomuto partition
def partition(array, start, end):
pivot = start
for i in range(start, end):
if array[i] <= array[end]:
array[i], array[pivot] = array[pivot], array[i]
pivot += 1
array[end], array[pivot] = array[pivot], array[end] # swap pivot value and value at pivot position
return pivot
# Hoare partition
def partition(array, start, end):
i, j = start, end - 1
while True:
while array[i] <= array[end] and i < j:
i += 1
while array[j] >= array[end] and i < j:
j -= 1
if i == j:
if array[i] <= array[end]:
i += 1
array[i], array[end] = array[end], array[i]
return i
else:
array[i], array[j] = array[j], array[i]