forked from codebasics/py
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquick_sort.py
More file actions
53 lines (39 loc) · 1.17 KB
/
quick_sort.py
File metadata and controls
53 lines (39 loc) · 1.17 KB
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# implementation of quick sort in python using hoare partition scheme
def swap(a, b, arr):
if a!=b:
tmp = arr[a]
arr[a] = arr[b]
arr[b] = tmp
def quick_sort(elements, start, end):
if start < end:
pi = partition(elements, start, end)
quick_sort(elements, start, pi-1)
quick_sort(elements, pi+1, end)
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
if __name__ == '__main__':
elements = [11,9,29,7,2,15,28]
# elements = ["mona", "dhaval", "aamir", "tina", "chang"]
quick_sort(elements, 0, len(elements)-1)
print(elements)
tests = [
[11,9,29,7,2,15,28],
[3, 7, 9, 11],
[25, 22, 21, 10],
[29, 15, 28],
[],
[6]
]
for elements in tests:
quick_sort(elements, 0, len(elements)-1)
print(f'sorted array: {elements}')