人脑可以轻松地处理视觉效果,而无需花费很长的代码来理解算法。在本文中,已实现了一个程序,该程序可视化了合并排序算法。
GUI(图形用户界面)是使用Python的pygame包实现的。
方法:
例子:
Input :
Press “Enter” key to Perform Visualization.
Press “r” key to generate new array.
Output :
Initial:
Visualizing:
Final:
以下是可视化“合并排序”算法的程序:
# Python implementation for visualizing merge sort.
import pygame
import random
pygame.font.init()
# Total window
screen = pygame.display.set_mode((900, 650))
# Title and Icon
pygame.display.set_caption("SORTING VISUALISER")
# Place any custom png file in same folder as the source code
# and mention it below and uncomment below two lines.
# img = pygame.image.load
# ('E:/Projects / Sorting Visualiser / sorticon.png')
# pygame.display.set_icon(img)
# Boolean variable to run the program in while loop
run = True
# Window size
width = 900
length = 600
array =[0]*151
arr_clr =[(0, 204, 102)]*151
clr_ind = 0
clr =[(0, 204, 102), (255, 0, 0),
(0, 0, 153), (255, 102, 0)]
fnt = pygame.font.SysFont("comicsans", 30)
fnt1 = pygame.font.SysFont("comicsans", 20)
# Generate new Array
def generate_arr():
for i in range(1, 151):
arr_clr[i]= clr[0]
array[i]= random.randrange(1, 100)
generate_arr()
def refill():
screen.fill((255, 255, 255))
draw()
pygame.display.update()
pygame.time.delay(20)
# Sorting Algo:Merge sort
def mergesort(array, l, r):
mid =(l + r)//2
if l
输出:
https://media.geeksforgeeks.org/wp-content/uploads/20200619162211/visualiser15-2020-06-19_16.16.37.mp4