-
Notifications
You must be signed in to change notification settings - Fork 91
/
Copy pathquicksort.py
48 lines (33 loc) · 935 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
# Quicksort with pivot always using first index as pivot
def quicksort_firstpivot(L):
if len(L) <= 1:
return L
pivot = L[0]
i = 0
for j in range(1, len(L)):
if L[j] < pivot:
L[j], L[i + 1] = L[i + 1], L[j]
i += 1
L[0], L[i] = L[i], L[0]
left = quicksort_firstpivot(L[:i])
right = quicksort_firstpivot(L[i + 1 :])
left.append(L[i])
result = left + right
return result
# Quicksort with pivot always using last index as pivot
def quicksort_lastpivot(x):
if len(x) <= 1:
return x
x[0], x[-1] = x[-1], x[0]
pivot = x[0]
i = 0
for j in range(1, len(x)):
if x[j] < pivot:
x[j], x[i + 1] = x[i + 1], x[j]
i += 1
x[0], x[i] = x[i], x[0]
left = quicksort_lastpivot(x[:i])
right = quicksort_lastpivot(x[i + 1 :])
left.append(x[i])
result = left + right
return result