人脑可以轻松处理视觉效果而不是长代码来理解算法。在本文中,实现了一个程序,该程序将合并排序算法可视化。
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
如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程和学生竞争性编程现场课程。