-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathsorting_algo_visualizer.py
581 lines (474 loc) · 14.2 KB
/
sorting_algo_visualizer.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
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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import os
import argparse
##### IMPLEMENTED ALGO #####
#BUBBLE
#QUICK
#HEAP
#INSERTION
#SELECTION
#COCKTAIL
#SHELL
#STOOGE
#COMB
#ODDEVEN
#TIM
#DUALPIVOTQUICK
#BITONIC
def bubblesort(A):
swaps = []
for i in range(len(A)):
for k in range(len(A) - 1, i, -1):
if (A[k] < A[k - 1]):
swaps.append([k, k - 1])
tmp = A[k]
A[k] = A[k - 1]
A[k - 1] = tmp
return swaps
def partition(array, begin, end):
pivot = begin
swaps = []
for i in range(begin + 1, end + 1):
if array[i] <= array[begin]:
pivot += 1
array[i], array[pivot] = array[pivot], array[i]
swaps.append([i, pivot])
array[pivot], array[begin] = array[begin], array[pivot]
swaps.append([pivot, begin])
return pivot, swaps
def quicksort(array, begin=0, end=None):
global swaps
swaps = []
if end is None:
end = len(array) - 1
def _quicksort(array, begin, end):
global swaps
if begin >= end:
return
pivot, newSwaps = partition(array, begin, end)
swaps += newSwaps
_quicksort(array, begin, pivot - 1)
_quicksort(array, pivot + 1, end)
_quicksort(array, begin, end)
return swaps
def dualpivotquicksort(A):
global swaps
swaps = []
def _partitionDualPivot(arr, low, high):
global swaps
if arr[low] > arr[high]:
arr[low], arr[high] = arr[high], arr[low]
swaps.append([low, high])
j = k = low + 1
g, p, q = high - 1, arr[low], arr[high]
while k <= g:
if arr[k] < p:
arr[k], arr[j] = arr[j], arr[k]
swaps.append([k,j])
j += 1
elif arr[k] >= q:
while arr[g] > q and k < g:
g -= 1
arr[k], arr[g] = arr[g], arr[k]
swaps.append([k,g])
g -= 1
if arr[k] < p:
arr[k], arr[j] = arr[j], arr[k]
swaps.append([k,j])
j += 1
k += 1
j -= 1
g += 1
arr[low], arr[j] = arr[j], arr[low]
swaps.append([low,j])
arr[high], arr[g] = arr[g], arr[high]
swaps.append([high,g])
return j, g
def _dualPivotQuickSort(arr, low, high):
global swaps
if low < high:
lp, rp = _partitionDualPivot(arr, low, high)
_dualPivotQuickSort(arr, low, lp - 1)
_dualPivotQuickSort(arr, lp + 1, rp - 1)
_dualPivotQuickSort(arr, rp + 1, high)
_dualPivotQuickSort(A,0,len(A)-1)
return swaps
def heapsort( aList ):
global swaps
swaps = []
# convert aList to heap
length = len( aList ) - 1
leastParent = length // 2
for i in range ( leastParent, -1, -1 ):
moveDown( aList, i, length )
# flatten heap into sorted array
for i in range ( length, 0, -1 ):
if aList[0] > aList[i]:
swaps.append([0, i])
swap( aList, 0, i )
moveDown( aList, 0, i - 1 )
return swaps
def moveDown( aList, first, last ):
global swaps
largest = 2 * first + 1
while largest <= last:
# right child exists and is larger than left child
if ( largest < last ) and ( aList[largest] < aList[largest + 1] ):
largest += 1
# right child is larger than parent
if aList[largest] > aList[first]:
swaps.append([largest, first])
swap( aList, largest, first )
# move down to largest child
first = largest;
largest = 2 * first + 1
else:
return # force exit
def swap( A, x, y ):
tmp = A[x]
A[x] = A[y]
A[y] = tmp
def insertionsort(A):
return _insertionsort(A, 0, len(A)-1)
def _insertionsort(A, left, right):
swaps = []
for i in range(left + 1, right + 1):
j = i
while j > left and A[j] < A[j - 1]:
A[j], A[j - 1] = A[j - 1], A[j]
swaps.append([j, j-1])
j -= 1
return swaps
def timsort(arr):
global swaps
swaps = []
MIN_MERGE = 32
def _calcMinRun(n):
"""Returns the minimum length of a
run from 23 - 64 so that
the len(array)/minrun is less than or
equal to a power of 2.
e.g. 1=>1, ..., 63=>63, 64=>32, 65=>33,
..., 127=>64, 128=>32, ...
"""
r = 0
while n >= MIN_MERGE:
r |= n & 1
n >>= 1
return n + r
n = len(arr)
minRun = _calcMinRun(n)
# Sort individual subarrays of size RUN
for start in range(0, n, minRun):
end = min(start + minRun - 1, n - 1)
swaps += _insertionsort(arr, start, end)
# Start merging from size RUN (or 32). It will merge
# to form size 64, then 128, 256 and so on ....
size = minRun
while size < n:
for left in range(0, n, 2 * size):
mid = min(n - 1, left + size - 1)
right = min((left + 2 * size - 1), (n - 1))
_merge(arr, left, mid, right)
size = 2 * size
return swaps
def selectionsort(A):
swaps = []
for i in range(len(A)):
jMin = i
for j in range(i+1,len(A)):
if A[j]<A[jMin]:
jMin = j
if jMin != i:
swaps.append([i, jMin])
swap(A, i, jMin)
return swaps
def cocktailsort(A):
swapped = True
swaps =[]
while swapped:
swapped = False
for i in range(len(A)-1):
if A[i] > A[i + 1]:
swaps.append([i,i+1])
swap(A, i, i+1)
swapped = True
if swapped == False:
break
for j in range(len(A)-2, -1,-1):
if A[j] > A[j + 1]:
swaps.append([j,j+1])
swap(A, j, j+1)
swapped = True
return swaps
def shellsort(A):
swaps =[]
n = len(A)
gap = n//2
while gap > 0:
for i in range(gap,n):
temp = A[i]
j = i
while j >= gap and A[j-gap] >temp:
A[j] = A[j-gap]
swaps.append([j, j-gap])
j -= gap
A[j] = temp
gap //= 2
return swaps
def stoogesort(A, begin=0, end=None):
global swaps
swaps = []
if end is None:
end = len(A) - 1
def _stoogesort(A, begin, end):
global swaps
if begin >= end:
return
if A[begin]>A[end]:
t = A[begin]
A[begin] = A[end]
A[end] = t
swaps.append([begin, end])
if end-begin+1 > 2:
t = (int)((end-begin+1)/3)
#first 2/3 elements
_stoogesort(A, begin, (end-t))
#last 2/3 elements
_stoogesort(A, begin+t, (end))
#2/3 elements
_stoogesort(A, begin, (end-t))
_stoogesort(A, begin, end)
return swaps
def combsort(data):
length = len(data)
shrink = 1.3
_gap = length
sorted = False
swaps = []
while not sorted:
_gap /= shrink
gap = int(_gap)
if gap <= 1:
sorted = True
gap = 1
for i in range(length - gap):
sm = gap + i
if data[i] > data[sm]:
data[i], data[sm] = data[sm], data[i]
swaps.append([i,sm])
sorted = False
return swaps
def oddevensort(arr):
swaps = []
n=len(arr)
isSorted = 0
while isSorted == 0:
isSorted = 1
temp = 0
for i in range(1, n-1, 2):
if arr[i] > arr[i+1]:
arr[i], arr[i+1] = arr[i+1], arr[i]
swaps.append([i,i+1])
isSorted = 0
for i in range(0, n-1, 2):
if arr[i] > arr[i+1]:
arr[i], arr[i+1] = arr[i+1], arr[i]
swaps.append([i,i+1])
isSorted = 0
return swaps
def _merge(arr, start, mid, end):
global swaps
start2 = mid + 1;
if (arr[mid] <= arr[start2]):
return;
while (start <= mid and start2 <= end):
if (arr[start] <= arr[start2]):
start += 1;
else:
value = arr[start2];
index = start2;
while (index != start):
arr[index] = arr[index - 1];
swaps.append([index,index-1])
index -= 1;
#swaps.append([start2, start])
arr[start] = value;
start += 1;
mid += 1;
start2 += 1;
#in-place
def mergesort(A):
global swaps
swaps = []
def _mergeSort(arr, l, r):
global swaps
if (l < r):
# Same as (l + r) / 2, but avoids overflow
# for large l and r
m = l + (r - l) // 2;
# Sort first and second halves
_mergeSort(arr, l, m);
_mergeSort(arr, m + 1, r);
_merge(arr, l, m, r);
_mergeSort(A, 0, len(A)-1)
return swaps
def bitonicsort(A):
global swaps
swaps = []
def _bitonicmerge(a, l, cnt, d):
global swaps
if cnt > 1:
k = cnt>>1
for i in range(l, l+k):
if (a[i] > a[i+k])^d:
a[i], a[i+k] = a[i+k], a[i]
swaps.append([i, i+k])
_bitonicmerge(a, l, k, d)
_bitonicmerge(a, l+k, k, d)
def _bitonicsort(a, l, cnt, d):
if cnt > 1:
k = cnt>>1
_bitonicsort(a, l, k, 0)
_bitonicsort(a, l+k, k, 1)
_bitonicmerge(a, l, cnt, d)
_bitonicsort(A, 0, len(A), 0)
return swaps
def videovisualize(sorter, cmap):
image = np.zeros((140, 128))
for i in range(image.shape[1]):
image[:,i] = i
for i in range(image.shape[0]):
np.random.shuffle(image[i,:])
maxMoves = 0
moves = []
sorter_to_use = eval(str(sorter)+'sort')
for i in range(image.shape[0]):
newMoves = []
newMoves = sorter_to_use(list(image[i,:]))
if len(newMoves) > maxMoves:
maxMoves = len(newMoves)
moves.append(newMoves)
def swap_pixels(row, places):
tmp = image[row,places[0]].copy()
image[row,places[0]] = image[row,places[1]]
image[row,places[1]] = tmp
currentMove = 0
imagelist=[]
fig = plt.figure(dpi=400, constrained_layout = True)
fig.patch.set_facecolor('black')
fig.set_size_inches(4.8, 4.8) #custom
plt.axis("off")
movie_image_step = maxMoves // 140
if movie_image_step == 0:
movie_image_step = 1
#unsorted image at start
for i in range(20):
imagelist.append((plt.imshow(image, cmap=cmap),))
while currentMove < maxMoves:
for i in range(image.shape[0]):
if currentMove < len(moves[i]):
swap_pixels(i, moves[i][currentMove])
if currentMove % movie_image_step == 0:
imagelist.append((plt.imshow(image, cmap=cmap),))
currentMove += 1
#sorted image at end
for i in range(20):
imagelist.append((plt.imshow(image, cmap=cmap),))
im_ani = animation.ArtistAnimation(
fig, imagelist, interval=60, repeat_delay=3000, blit=True
)
os.makedirs('output/video', exist_ok=True)
im_ani.save(('output/video/sample-'+str(sorter)+'-'+str(movie_image_step)+str(cmap)+ ".gif"))
def imagevisualize(sorter, order, cmap):
image = get_list_for_image(order)
newMoves = []
sorter_to_use = eval(str(sorter)+'sort')
newMoves = sorter_to_use(list(image))
newimage=image
temp = len(newMoves) // 700
if temp ==0:
temp=1
imagelist=[]
fig = plt.figure(dpi=200)
fig.patch.set_facecolor('black')
plt.axis("off")
def swap_pixels(places):
tmp = image[places[0]].copy()
image[places[0]] = image[places[1]]
image[places[1]] = tmp
for i in range(len(newMoves)):
swap_pixels(newMoves[i])
if i % temp == 0:
newimage=np.vstack([newimage,image])
for x in range(10):
newimage=np.vstack([newimage,image])
plt.imshow(newimage,cmap=cmap)
os.makedirs('output/image', exist_ok=True)
plt.imsave('output/image/sample-'+str(sorter)+'-'+str(order)+'-'+str(temp)+str(cmap)+ ".png",newimage, dpi=1200, cmap=cmap)
def get_list_for_image(order):
image = np.zeros((300))
if order =='random':
for i in range(image.shape[0]):
image[i] = i
np.random.shuffle(image[:])
if order == 'reverse':
j=image.shape[0]-1
for i in range(image.shape[0]):
image[i] = j
j-=1
if order =='interleave':
x = 0
y = image.shape[0]-1
for i in range(image.shape[0]):
if i%2 == 0:
image[i] = x
x+=1
else:
image[i]=y
y-=1
if order =='swappedhalf':
x=image.shape[0]//2
for i in range(image.shape[0]//2):
image[i]=x
x+=1
x=0
for i in range(image.shape[0]//2, image.shape[0]):
image[i]=x
x+=1
if order =='interleavehalf':
x = 0
y = image.shape[0]-1
for i in range(image.shape[0]):
if i%2 == 0:
image[x] = i
x+=1
else:
image[y]=i
y-=1
return image
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Sorting Algorithms Visualizer. By default, produce a bubblesort visualization"
)
parser.add_argument(
"-sorter", type=str, default="bubble", help="sorting algorithm to use."
)
parser.add_argument(
"-out", type=str, default="video", help="Type of output to produce, -o video or -o image"
)
parser.add_argument(
"-order", type=str, default="random", help="Starting order of the list. Default to random."
)
parser.add_argument(
"-c", type=str, default="viridis", help="matplotlib colormap."
)
args = parser.parse_args()
if args.out == 'video':
videovisualize(sorter=args.sorter, cmap=args.c)
elif args.out =='image':
imagevisualize(sorter=args.sorter, order=args.order,cmap=args.c)
else:
videovisualize(args.sorter)