-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadd mergesort python def.py
More file actions
283 lines (236 loc) · 7.18 KB
/
add mergesort python def.py
File metadata and controls
283 lines (236 loc) · 7.18 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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
#!/usr/bin/env python3
"""
sorting_animation.py
A minimal sorting algorithm animation:
Sorts a shelf of 10 blocks using insertion
sort, selection sort and quicksort.
Shelfs are implemented using builtin lists.
Blocks are turtles with shape "square", but
stretched to rectangles by shapesize()
---------------------------------------
To exit press space button
---------------------------------------
"""
from turtle import *
import random
class Block(Turtle):
def __init__(self, size):
self.size = size
Turtle.__init__(self, shape="square", visible=False)
self.pu()
self.shapesize(size * 1.5, 1.5, 2) # square-->rectangle
self.fillcolor("black")
self.st()
def glow(self):
self.fillcolor("red")
def unglow(self):
self.fillcolor("pink")
def __repr__(self):
return "Block size: {0}".format(self.size)
class Shelf(list):
def __init__(self, y):
"create a shelf. y is y-position of first block"
self.y = y
self.x = -150
def push(self, d):
width, _, _ = d.shapesize()
# align blocks by the bottom edge
y_offset = width / 2 * 20
d.sety(self.y + y_offset)
d.setx(self.x + 34 * len(self))
self.append(d)
def _close_gap_from_i(self, i):
for b in self[i:]:
xpos, _ = b.pos()
b.setx(xpos - 34)
def _open_gap_from_i(self, i):
for b in self[i:]:
xpos, _ = b.pos()
b.setx(xpos + 34)
def pop(self, key):
b = list.pop(self, key)
b.glow()
b.sety(200)
self._close_gap_from_i(key)
return b
def insert(self, key, b):
self._open_gap_from_i(key)
list.insert(self, key, b)
b.setx(self.x + 34 * key)
width, _, _ = b.shapesize()
# align blocks by the bottom edge
y_offset = width / 2 * 20
b.sety(self.y + y_offset)
b.unglow()
def pop_without_closing_gap(self, key):
#b = list.pop(self, key)
b = self[key]
b.glow()
b.sety(200)
#self._close_gap_from_i(key)
return b
def insert_without_opening_gap(self, key, b):
#self._open_gap_from_i(key)
#list.insert(self, key, b)
self[key] = b
b.setx(self.x + 34 * key)
width, _, _ = b.shapesize()
# align blocks by the bottom edge
y_offset = width / 2 * 20
b.sety(self.y + y_offset)
b.unglow()
def isort(shelf):
length = len(shelf)
for i in range(1, length):
hole = i
while hole > 0 and shelf[i].size < shelf[hole - 1].size:
hole = hole - 1
shelf.insert(hole, shelf.pop(i))
return
def ssort(shelf):
length = len(shelf)
for j in range(0, length - 1):
imin = j
for i in range(j + 1, length):
if shelf[i].size < shelf[imin].size:
imin = i
if imin != j:
shelf.insert(j, shelf.pop(imin))
def partition(shelf, left, right, pivot_index):
pivot = shelf[pivot_index]
shelf.insert(right, shelf.pop(pivot_index))
store_index = left
for i in range(left, right): # range is non-inclusive of ending value
if shelf[i].size < pivot.size:
shelf.insert(store_index, shelf.pop(i))
store_index = store_index + 1
shelf.insert(store_index, shelf.pop(right)) # move pivot to correct position
return store_index
def qsort(shelf, left, right):
if left < right:
pivot_index = left
pivot_new_index = partition(shelf, left, right, pivot_index)
qsort(shelf, left, pivot_new_index - 1)
qsort(shelf, pivot_new_index + 1, right)
def msort(shelf,start_pos,end_pos):
if start_pos == end_pos:
return shelf[start_pos:end_pos+1]
l = end_pos - start_pos + 1
h1 = msort(shelf, start_pos, start_pos+l//2-1)
h2 = msort(shelf, start_pos+l//2, end_pos)
return merge(shelf, h1, h2, start_pos)
def randomize():
disable_keys()
clear()
target = list(range(10))
random.shuffle(target)
for i, t in enumerate(target):
for j in range(i, len(s)):
if s[j].size == t + 1:
s.insert(i, s.pop(j))
show_text(instructions1)
show_text(instructions2, line=1)
enable_keys()
def show_text(text, line=0):
line = 20 * line
goto(0,-250 - line)
write(text, align="center", font=("Courier", 16, "bold"))
def start_msort():
disable_keys()
clear()
show_text("Merge Sort")
qsort(s, 0, len(s) - 1)
clear()
show_text(instructions1)
show_text(instructions2, line=1)
enable_keys()
def start_ssort():
disable_keys()
clear()
show_text("Selection Sort")
ssort(s)
clear()
show_text(instructions1)
show_text(instructions2, line=1)
enable_keys()
def start_isort():
disable_keys()
clear()
show_text("Insertion Sort")
isort(s)
clear()
show_text(instructions1)
show_text(instructions2, line=1)
enable_keys()
def start_qsort():
disable_keys()
clear()
show_text("Quicksort")
qsort(s, 0, len(s) - 1)
clear()
show_text(instructions1)
show_text(instructions2, line=1)
enable_keys()
def merge(shelf,h1,h2,h1_offset):
h1_pos = h2_pos = r_pos = 0
n = len(h1)+len(h2)
r = [None]*n
for i in range(0,n):
if h1_pos == len(h1):
r[r_pos] = h2[h2_pos]
h2_pos +=1
elif h2_pos == len(h2):
r[r_pos] = h1[h1_pos]
h1_pos += 1
else:
if h1[h1_pos].size < h2[h2_pos].size:
r[r_pos] = h1[h1_pos]
h1_pos += 1
else:
r[r_pos] = h2[h2_pos]
h2_pos += 1
r_pos += 1
visualize_merge(shelf,r,h1_offset)
return r
def visualize_merge(shelf,r,offset):
b = [None]*len(r)
for j in range(0,len(r)):
for i in range(0,len(shelf)):
if shelf[i] == r[j]:
b[j] = shelf.pop_without_closing_gap(i)
break
for j in range(0,len(r)):
shelf.insert_without_opening_gap(offset+j, b[j])
def init_shelf():
global s
s = Shelf(-200)
vals = (4, 2, 8, 9, 1, 5, 10, 3, 7, 6)
for i in vals:
s.push(Block(i))
def disable_keys():
onkey(None, "m")
onkey(None, "s")
onkey(None, "i")
onkey(None, "q")
onkey(None, "r")
def enable_keys():
onkey(start_msort, "m")
onkey(start_isort, "i")
onkey(start_ssort, "s")
onkey(start_qsort, "q")
onkey(randomize, "r")
onkey(bye, "space")
def main():
getscreen().clearscreen()
ht(); penup()
init_shelf()
show_text(instructions1)
show_text(instructions2, line=1)
enable_keys()
listen()
return "EVENTLOOP"
instructions1 = "press i for insertion sort, s for selection sort, q for quicksort, m for merge sort"
instructions2 = "spacebar to quit, r to randomize"
if __name__=="__main__":
msg = main()
mainloop()