-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathquicksort.py
77 lines (66 loc) · 848 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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
def quicksorted(a):
if len(a) <= 1:
return a
# selecting pivot using
# median of 3 method
mid = len(a) // 2
if a[mid] < a[0]:
a[0], a[mid] = a[mid], a[0]
if a[-1] < a[0]:
a[-1], a[0] = a[0], a[-1]
if a[mid] < a[-1]:
a[-1], a[mid] = a[mid], a[-1]
pivot = a[-1]
L = []
R = []
M = []
for x in a:
if x < pivot:
L.append(x)
elif x == pivot:
M.append(x)
else:
R.append(x)
return (quicksorted(L)) + M + (quicksorted(R))
if __name__ == '__main__':
a = [
55555,
666666,
1,
999999999,
1010101010,
88888888,
4444,
333,
7777777,
22,
]
for x in a:
print(x)
print("\nPerforming Quicksort\n")
a = quicksorted(a)
for x in a:
print(x)
""" Output
55555
666666
1
999999999
1010101010
88888888
4444
333
7777777
22
Sorting
1
22
333
4444
55555
666666
7777777
88888888
999999999
1010101010
"""