-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquick_sort.py
More file actions
33 lines (25 loc) · 820 Bytes
/
quick_sort.py
File metadata and controls
33 lines (25 loc) · 820 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
26
27
28
29
30
31
32
33
# Hoare's partition
def swap(a, b, arr):
if a != b:
arr[a], arr[b] = arr[b], arr[a]
def partition(elements, start, end):
pivot_index = start
pivot = elements[pivot_index]
while start < end:
while start < len(elements) and elements[start] <= pivot:
start += 1
while elements[end] > pivot:
end -= 1
if start < end:
swap(start, end, elements)
swap(pivot_index, end, elements)
return(end)
def quick_sort(elements, start, end):
if start < end:
p1 = partition(elements, start, end)
quick_sort(elements, start, p1-1)
quick_sort(elements, p1 + 1, end)
if __name__ == "__main__":
elements = [11, 9, 29, 7, 2, 15, 28]
quick_sort(elements, 0, len(elements)-1)
print(elements)