-
Notifications
You must be signed in to change notification settings - Fork 0
/
sorts.py
70 lines (50 loc) · 1.56 KB
/
sorts.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
import random
import math
ARRAYSIZE = 10
def swap(array, x, y):
tmp = array[x]
array[x] = array[y]
array[y] = tmp
def compare_lt(array, x, y):
return array[x] < array[y]
def bubblesort(array, start, stop):
# Bubblesort it... it's the only way to be sure
for _ in range(math.ceil((len(array)))):
for x in range(len(array) - 1):
if compare_lt(array, x, x + 1):
swap(array, x, x + 1)
def quicksort(array, start, stop):
if stop - start < 2:
return True
import pudb
pudb.set_trace() # breakpoint defefe8b //
larger_index = stop - 2
smaller_index = start
# the "whole" starts where the pivot does
pivot = array[stop - 1]
hole = stop - 1
while larger_index + 1 > smaller_index:
if compare_lt(array, stop - 1, larger_index):
# good case, this is the right side
# just shift the whole and continue!
array[hole] = array[larger_index]
larger_index -= 1
hole -= 1
else:
# gotta put it on the other side
swap(array, larger_index, smaller_index)
smaller_index += 1
array[hole] = pivot
quicksort(array, start, hole)
quicksort(array, hole + 1, stop)
def test_sort(sortfn):
random.seed('ladyred')
array = [random.randrange(ARRAYSIZE) for x in range(ARRAYSIZE)]
sortfn(array, 0, len(array))
for x, y in zip(array, array[1:]):
assert x < y
def main():
test_sort(quicksort)
test_sort(bubblesort)
if __name__ == '__main__':
main()