-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquick_sort.py
More file actions
68 lines (61 loc) · 1.95 KB
/
quick_sort.py
File metadata and controls
68 lines (61 loc) · 1.95 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
'''
Quick Sort
'''
from sort_check import sort_check, sort_check1
# Automatically selects a pivot value, then moves values smaller/larger than
# the pivot value to left/right ends of the list.
def pivot_sort(l, begin, end):
def get_pivot_idx():
'''Use middle-value of three samples (left/center/right)'''
middle = (begin + end) // 2
sample_values = (l[begin], l[middle], l[end])
if sample_values[0] <= sample_values[1]:
if sample_values[1] <= sample_values[2]: # b < m < e
return middle
elif sample_values[2] <= sample_values[0]: # e < b < m
return begin
else:
return end
else:
if sample_values[1] >= sample_values[2]: # b > m > e
return middle
elif sample_values[2] >= sample_values[0]: # e > b > m
return begin
else:
return end
pivot_idx = get_pivot_idx()
pivot_value = l[pivot_idx]
l[pivot_idx] = l[begin]
left = begin + 1
right = end
hole = begin
hole_on_left = True
while left <= right:
if hole_on_left:
if l[right] < pivot_value:
l[hole] = l[right]
hole = right
hole_on_left = False
right -= 1
else:
if l[left] > pivot_value:
l[hole] = l[left]
hole = left
hole_on_left = True
left += 1
l[hole] = pivot_value
return hole
# Performs the pivot rearragement and then calls quicksort recursively on both
# halves.
def _quick_sort(l, begin, end):
if begin == end:
return
pivot_idx = pivot_sort(l, begin, end)
if pivot_idx > begin:
_quick_sort(l, begin, pivot_idx - 1)
if pivot_idx < end:
_quick_sort(l, pivot_idx + 1, end)
def quick_sort(l):
_quick_sort(l, 0, len(l) - 1)
sort_check1(quick_sort, 0b111)
sort_check(quick_sort)