-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathVisSortingAlgo.py
More file actions
438 lines (353 loc) · 12 KB
/
VisSortingAlgo.py
File metadata and controls
438 lines (353 loc) · 12 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
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
import numpy as np
import matplotlib.pyplot as plt
import random
#******************************************************************
#Variables for the unsorted list of integers
length = 50
max = 100
min = 1
randomNums = []
step = 0
#******************************************************************
#Basic Sorting Algorithm Functions (Bubble, Merge, BOGO, Selection, Insertion)
#Bubble Sort
def BubbleSort(randArray):
n = len(randArray)
step = 0
for j in range(n):
print(j,"/",n)
for i in range(n-j-1):
step +=1
#Compare first and second num
numOne = randArray[i]
numTwo = randArray[i+1]
if numOne>numTwo:
#Change order of nums if first num is greater than second num
randArray[i],randArray[i+1] = randArray[i+1], randArray[i]
#Print number of steps for sorting
print("Total number of steps: ",step)
return randArray
#Merge Sort
def MergeSort(randArray):
n = len(randArray)
#Divide array if more than one element
if n > 1:
mid = n // 2
#Divide array into two halves
left_half = randArray[:mid]
right_half = randArray[mid:]
#Recursively sort both halves
MergeSort(left_half)
MergeSort(right_half)
i = j = k = 0
#Merge the halves
while i < len(left_half) and j < len(right_half):
if left_half[i] < right_half[j]:
randArray[k] = left_half[i]
i += 1
else:
randArray[k] = right_half[j]
j += 1
k += 1
# Checking if any elements were left in the left_half
while i < len(left_half):
randArray[k] = left_half[i]
i += 1
k += 1
# Checking if any elements were left in the right_half
while j < len(right_half):
randArray[k] = right_half[j]
j += 1
k += 1
#Return sorted array
return randArray
#Bogo Sort
def BogoSort(randArray):
step = 0
#Randomly arrange array until sorted correctly
while not IsSorted(randArray):
random.shuffle(randArray)
step +=1
print(step)
return randArray
#Checking if the current function is sorted (for Bogo Sort def)
def IsSorted(arr):
for i in range (len(arr)-1):
if arr[i] > arr[i+1]:
return False
return True
#Selection Sort
def SelectionSort(randArray):
n = len(randArray)
step = 0
#Find the smallest element and swap it with the first unsorted element in the array
for i in range(n):
for j in range(n,i):
step += 1
if randArray[j-1] < randArray[j]:
randArray[j-1], randArray[j] = randArray[j], randArray[j-1]
print(randArray)
return randArray
#Insertion Sort
def InsertionSort(randArray):
n = len(randArray)
#Iterate through array and find location for each next integer in the series
for i in range (1, n):
move = randArray[i]
j = i-1
while j >=0 and move < randArray[j]:
randArray[j+1] = randArray[j]
j -= 1
randArray[j+1] = move
return randArray
#******************************************************************
#Visualized Sorting Algorithm Functions (Bubble, Merge, BOGO, Selection, Insertion)
#Bubble Sort Visualization
def VisualizeBubbleSort(arr,time):
#Check if the array is empty
if not arr:
print("The array is empty.")
return
print("Initial array:", arr)
n = len(arr)
step = 0
plt.ion()
fig, ax = plt.subplots()
for j in range(n):
print(f"{j + 1} / {n}")
for i in range(n - j - 1):
step += 1
numOne = arr[i]
numTwo = arr[i + 1]
#Clear graph
ax.clear()
#Create blue bars
ax.bar(range(n), arr, color='blue')
#Highlight current bars being compared
ax.bar(i, numOne, color='red')
ax.bar(i + 1, numTwo, color='green')
#Swap if first num is greater than second num
if numOne > numTwo:
arr[i], arr[i + 1] = arr[i + 1], arr[i]
#Titles and pause intervals between each iteration
ax.set_title(f'Bubble Sort: Step {step}')
ax.set_xlabel('Index')
ax.set_ylabel('Value')
plt.pause(time)
plt.ioff()
plt.show()
#Merge Sort Visualization
def VisualizeMergeSort(arr, time):
global step
# Check if the array is empty
if not arr:
print("The array is empty.")
return
print("Initial array:", arr)
#Set up environment
n = len(arr)
plt.ion()
fig, ax = plt.subplots()
#Recursive function for merge sort with visualization
def merge_sort_visualize(arr, left_index, right_index):
global step
if left_index < right_index:
mid = (left_index + right_index) // 2
#Recursive calls to sort left and right halves
merge_sort_visualize(arr, left_index, mid)
merge_sort_visualize(arr, mid + 1, right_index)
# Merge the sorted halves
merge(arr, left_index, mid, right_index)
# Function to merge two halves and visualize
def merge(arr, left_index, mid, right_index):
global step
left_half = arr[left_index:mid + 1]
right_half = arr[mid + 1:right_index + 1]
i = j = 0
k = left_index
while i < len(left_half) and j < len(right_half):
step += 1
ax.clear()
ax.bar(range(n), arr, color='blue')
#Highlight the merging area
ax.bar(range(left_index, right_index + 1), arr[left_index:right_index + 1], color='green')
ax.bar(k, arr[k], color='red')
if left_half[i] <= right_half[j]:
arr[k] = left_half[i]
i += 1
else:
arr[k] = right_half[j]
j += 1
k += 1
ax.set_title(f'Merge Sort: Step {step}')
ax.set_xlabel('Index')
ax.set_ylabel('Value')
plt.pause(time)
#Check if any elements were left in left_half
while i < len(left_half):
step += 1
arr[k] = left_half[i]
ax.clear()
ax.bar(range(n), arr, color='blue')
ax.bar(range(left_index, right_index + 1), arr[left_index:right_index + 1], color='green')
ax.bar(k, arr[k], color='red')
i += 1
k += 1
ax.set_title(f'Merge Sort: Step {step}')
plt.pause(time)
#Check if any elements were left in right_half
while j < len(right_half):
step += 1
arr[k] = right_half[j]
ax.clear()
ax.bar(range(n), arr, color='blue')
ax.bar(range(left_index, right_index + 1), arr[left_index:right_index + 1], color='green')
ax.bar(k, arr[k], color='red')
j += 1
k += 1
ax.set_title(f'Merge Sort: Step {step}')
plt.pause(time)
# Initial call to recursive merge sort function
merge_sort_visualize(arr, 0, len(arr) - 1)
plt.ioff()
plt.show()
#Bogo Sort Visualization
def VisualizeBogoSort(arr, time):
if not arr:
print("The array is empty.")
return
print("Initial array:", arr)
#Set up environment
n = len(arr)
step = 0
plt.ion()
fig, ax = plt.subplots()
while not IsSorted(arr):
#Randomize the array
random.shuffle(arr)
step += 1
#Clear the previous bar graph
ax.clear()
ax.bar(range(n), arr, color='blue')
#Titles and pause intervals between each iteration
ax.set_title(f'Bogo Sort: Step {step}')
ax.set_xlabel('Index')
ax.set_ylabel('Value')
plt.pause(time)
plt.ioff()
plt.show()
#Selection Sort Visualization
def VisualizeSelectionSort(arr, time):
if not arr:
print("The array is empty.")
return
print("Initial array:", arr)
# Set up visualization environment
n = len(arr)
step = 0
plt.ion() # Turn on interactive mode
fig, ax = plt.subplots()
# Selection Sort algorithm with visualization
for i in range(n):
min_idx = i
for j in range(i + 1, n):
step += 1
#Clear graph
ax.clear()
ax.bar(range(n), arr, color='blue')
#Highlight element being checked
ax.bar(j, arr[j], color='red')
#Highlight current min element
ax.bar(min_idx, arr[min_idx], color='green')
# If a new minimum is found, update min_idx
if arr[j] < arr[min_idx]:
min_idx = j
#Titles and pause intervals between each iteration
ax.set_title(f'Selection Sort: Step {step}')
ax.set_xlabel('Index')
ax.set_ylabel('Value')
plt.pause(time)
# Swap the min element with the next unsorted element (at index i)
arr[i], arr[min_idx] = arr[min_idx], arr[i]
#Clear the previous bar graph
ax.clear()
ax.bar(range(n), arr, color='blue')
ax.bar(i, arr[i], color='green')
#Titles and pause intervals between each iteration
ax.set_title(f'Selection Sort: Step {step}')
ax.set_xlabel('Index')
ax.set_ylabel('Value')
plt.pause(time)
plt.ioff()
plt.show()
#Insertion Sort Visualization
def VisualizeInsertionSort(arr, time):
if len(arr) == 0:
print("The array is empty.")
return
print("Initial array:", arr)
#Set up environment
n = len(arr)
step = 0
plt.ion()
fig, ax = plt.subplots()
for i in range(1, n):
key = arr[i]
j = i - 1
height = arr[j+1]
#Clear the previous bar graph
ax.clear()
ax.bar(range(n), arr, color='blue')
#Highlight bar being moved
ax.bar(j+1, height, color='red')
#Titles and pause intervals between each iteration
ax.set_title(f'Insertion Sort: Step {step}')
ax.set_xlabel('Index')
ax.set_ylabel('Value')
plt.pause(time)
#Set height of key bar
#Shift elements that are greater than the key
while j >= 0 and arr[j] > key:
step += 1
arr[j + 1] = arr[j]
j -= 1
#Clear the previous bar graph
ax.clear()
ax.bar(range(n), arr, color='blue')
#Highlight bar being shifted
ax.bar(j + 1, height, color='red')
#Titles and pause intervals between each iteration
ax.set_title(f'Insertion Sort: Step {step}')
ax.set_xlabel('Index')
ax.set_ylabel('Value')
plt.pause(time)
#Insert the key
arr[j + 1] = key
#Visualization after inserting the key
step += 1
ax.clear()
ax.bar(range(n), arr, color='blue')
ax.bar(j + 1, arr[j + 1], color='green')
#Titles and pause intervals between each iteration
ax.set_title(f'Insertion Sort: Step {step}')
ax.set_xlabel('Index')
ax.set_ylabel('Value')
plt.pause(time)
plt.ioff()
plt.show()
#******************************************************************
#Change any variables (if needed)
length = length
max = max
min = min
#Create a list of random unsorted numbers
for i in range(length):
randomNums.append(random.randint(min,max))
#Call the functions below to see the visualizations of each sorting algorithm
#Uncomment below to activate
#VisualizeBubbleSort(randomNums,0.001)
#VisualizeMergeSort(randomNums,0.001)
#VisualizeBogoSort(randomNums, 0.001)
#VisualizeSelectionSort(randomNums, 0.001)
#isualizeInsertionSor(randomNums,0.001)
#******************************************************************