forked from gcallah/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsorting.py
More file actions
227 lines (196 loc) · 5.58 KB
/
sorting.py
File metadata and controls
227 lines (196 loc) · 5.58 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This file contains Python implementations of sorting algorithms from
Intro to Algorithms (Cormen et al.)
The aim here is not efficient Python implementations (we'd just call
the native sort if we wanted that) but to duplicate the pseudo-code
in the book as closely as possible.
Also, since the goal is to help students to see how the algorithm
works, there are print statements placed at key points in the code.
I have been helped by code from http://interactivepython.org/
in creating these examples.
The performance of each function is stated in the docstring, and
loop invariants are expressed as assert statements when they
are not too complex.
This file contains:
quicksort()
rand_quicksort()
insert_sort()
merge_sort()
bubble_sort()
And auxilliary functions that these sorts use, such as
swap().
"""
import sys
import random
MAX_SENTINEL = sys.maxsize
MIN_SENTINEL = -1 * sys.maxsize
def swap(l, i, j):
"""
Since several sort algorithms need to swap list
elements, we provide a swap function.
Args:
l: the list
i, j: the indices of the elements to swap.
"""
temp = l[i]
l[i] = l[j]
l[j] = temp
def merge_sort(l):
"""
Args:
l: the list to sort
Returns: a sorted list
Performance: Θ(n * lg n)
"""
length = len(l)
if length <= 1:
return l
else:
print("Splitting ", l)
mid = length // 2
left = l[:mid]
right = l[mid:]
left = merge_sort(left)
right = merge_sort(right)
return merge(left, right)
def merge(left, right):
"""
Helper function for merge_sort: this actually
merges the split and already sorted sub-lists.
Args:
left: a sorted list
right: a sorted list
"""
sorted = []
left.append(MAX_SENTINEL)
right.append(MAX_SENTINEL)
i = 0
j = 0
for k in range(len(right) + len(left) - 2):
if left[i] <= right[j]:
print("Appending " + str(left[i])
+ " to " + str(sorted))
sorted.append(left[i])
i += 1
else:
print("Appending " + str(right[j])
+ " to " + str(sorted))
sorted.append(right[j])
j += 1
return sorted
def insert_sort(l):
"""
Args:
l: the list to sort
Returns: a sorted list.
Performance: Θ(n**2)
"""
for j in range(1, len(l)):
key = l[j]
print("key = " + str(key))
i = j - 1
while i >= 0 and l[i] > key:
print("moving " + str(l[i]) + " forward one.")
l[i + 1] = l[i]
i -= 1
l[i + 1] = key
return l
def bubble_sort(l):
"""
Args:
l: the list to sort
Returns: a sorted list.
Performance: Θ(n**2)
"""
for i in range(0, len(l) - 1):
for j in range(len(l) - 1, i, -1):
if l[j] < l[j - 1]:
print("Swapping " + str(l[j]) + " and "
+ str(l[j - 1]))
swap(l, j, j - 1)
return l
def quicksort(l, p=None, r=None):
"""
Args:
l: the list to sort
p: the first index in a partition
r: the last index in a partition
Returns: a sorted list.
Performance:
Worst case: Θ(n**2)
Expected case: Θ(n * lg n)
Sorts in place.
"""
if p is None:
p = 0
if r is None:
r = len(l) - 1
if p < r:
q = partition(l, p, r)
print("Partitioning list at index " + str(q))
print("The list is now: " + str(l))
quicksort(l, p, q - 1)
quicksort(l, q + 1, r)
def partition(l, p, r):
"""
Helper function for quicksort.
Returns: the new partition index.
"""
x = l[r]
print("Our pivot element x = " + str(x))
i = p - 1
for j in range(p, r):
if l[j] <= x:
i += 1
print("i = " + str(i) + " and j = " + str(j))
if i != j:
print("Swapping elements " + str(l[i]) + " and "
+ str(l[j]))
swap(l, i, j)
if (i + 1) != r:
swap(l, i + 1, r)
print("Swapping elements " + str(l[i + 1]) + " and "
+ str(l[r]))
return i + 1
def rand_quicksort(l, p=None, r=None):
"""
Args:
l: the list to sort
p: the first index in a partition
r: the last index in a partition
Returns: a sorted list.
Performance:
Worst case: Θ(n**2)
Expected case: Θ(n * lg n)
Sorts in place.
This is a version of quicksort where the pivot
element is chosen randomly. By randomly choosing the pivot,
we expect a better balanced split of the input
list on average.
quicksort() and rand_quicksort() could easily be
rewritten as a single function taking a pointer
to the partition function to be used.
"""
if p is None:
p = 0
if r is None:
r = len(l) - 1
if p < r:
q = rand_partition(l, p, r)
print("Partitioning list at index " + str(q))
print("The list is now: " + str(l))
rand_quicksort(l, p, q - 1)
rand_quicksort(l, q + 1, r)
def rand_partition(l, p, r):
"""
This function simply chooses a random index value between
p and r, swaps that value with the one at r,
and then calls partition on the new List.
"""
i = random.randint(p, r)
print("We have randomly chosen between values " + str(p) +
" and " + str(r) + ": " + str(i) + " as our pivot.")
swap(l, i, r)
return partition(l, p, r)