-
Notifications
You must be signed in to change notification settings - Fork 54
Expand file tree
/
Copy pathQuickSort.py
More file actions
36 lines (28 loc) · 799 Bytes
/
Copy pathQuickSort.py
File metadata and controls
36 lines (28 loc) · 799 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
34
35
36
def quick_sort(arr):
"""Returns the array arr sorted using the quick sort algorithm
>>> import random
>>> unordered = [i for i in range(5)]
>>> random.shuffle(unordered)
>>> quick_sort(unordered)
[0, 1, 2, 3, 4]
"""
less = []
equal = []
greater = []
if len(arr) < 1:
return arr
pivot = arr[len(arr) // 2] # pivot at mid point
for num in arr:
if num < pivot:
less.append(num)
elif num == pivot:
equal.append(num)
elif num > pivot:
greater.append(num)
return quick_sort(less) + equal + quick_sort(greater)
if __name__ == "__main__":
import random
unordered = [i for i in range(5)]
random.shuffle(unordered)
sort = quick_sort(unordered)
print(sort)