-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathquicksort.py
59 lines (51 loc) · 1.43 KB
/
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
from math import floor
from numpy import median, where
def quicksort(data, index):
'''
:param data:
:param index: string which can take the value of first, last or median
:return:
'''
if len(data) == 1:
return data
else:
pivot_loc, pivot_val = pivot_setter(data, index)
data.pop(pivot_loc)
left, right = partition(data, pivot_val)
left.append(pivot_val)
left += right
return left
def partition(data, pivot):
def swap(i, j):
temp = data[i]
data[i] = data[j]
data[j] = temp
i = 0
j = len(data) - 1
while i < j:
item = data[i]
if item < pivot:
i += 1
else:
swap(i, j)
j -= 1
return data[0:i], data[i::]
def pivot_setter(data, index):
'''
:param data:
:param index: string which can take the value of first, last or median
:return: index of the quick sort pivot and the value of the pivot
'''
if index == 'first':
return 0, data[0]
elif index == 'last':
return -1, data[-1]
elif index == 'median':
n = len(index)
median_idx = floor(n / 2)
pot_idx = [0, -1, median_idx]
pot_pivots = [data[0], data[-1], data[median_idx]]
piv_val = median(pot_pivots)
piv_idx = where(pot_pivots == piv_val)
return pot_idx[piv_idx], piv_val
print(quicksort([2, 4, 10, 1, 3], 'first'))