-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathsorting.py
82 lines (61 loc) · 2.45 KB
/
sorting.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
78
79
80
81
82
""" Basic Sorting Algorithms Implemented in Python """
import random
import heapq
def bubble_sort(items):
""" Implementation of bubble sort """
for i in range(len(items)):
for j in range(len(items)-1-i):
if items[j] > items[j+1]:
items[j], items[j+1] = items[j+1], items[j] # Swap!
def insertion_sort(items):
""" Implementation of insertion sort """
for i in range(1, len(items)):
j = i
while j > 0 and items[j] < items[j-1]:
items[j], items[j-1] = items[j-1], items[j]
j -= 1
def merge_sort(items):
""" Implementation of mergesort """
if len(items) > 1:
mid = len(items) / 2 # Determine the midpoint and split
left = items[0:mid]
right = items[mid:]
merge_sort(left) # Sort left list in-place
merge_sort(right) # Sort right list in-place
l, r = 0, 0
for i in range(len(items)): # Merging the left and right list
lval = left[l] if l < len(left) else None
rval = right[r] if r < len(right) else None
if (lval and rval and lval < rval) or rval is None:
items[i] = lval
l += 1
elif (lval and rval and lval >= rval) or lval is None:
items[i] = rval
r += 1
else:
raise Exception('Could not merge, sub arrays sizes do not match the main array')
def quick_sort(items):
""" Implementation of quick sort """
if len(items) > 1:
pivot_index = len(items) / 2
smaller_items = []
larger_items = []
for i, val in enumerate(items):
if i != pivot_index:
if val < items[pivot_index]:
smaller_items.append(val)
else:
larger_items.append(val)
quick_sort(smaller_items)
quick_sort(larger_items)
items[:] = smaller_items + [items[pivot_index]] + larger_items
def heap_sort(items):
""" Implementation of heap sort """
heapq.heapify(items)
items[:] = [heapq.heappop(items) for i in range(len(items))]
if __name__ == '__main__':
random_items = [random.randint(-50, 100) for c in range(32)]
print 'Before: ', random_items
insertion_sort(random_items) # Replace the funtion name here to
# try any of the other algorithms
print 'After : ', random_items