栏目分类:
子分类:
返回
文库吧用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
文库吧 > IT > 软件开发 > 后端开发 > Python

使用 PyGame 的冒泡排序可视化工具

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用 PyGame 的冒泡排序可视化工具

使用 PyGame 的冒泡排序可视化工具

原文地址

在本文中,我们将看到如何使用 PyGame 可视化冒泡排序算法,即当 pygame 应用程序启动时,我们可以看到具有不同高度的未排序条,当我们单击空格键时,它开始以冒泡排序方式排列,即在每次迭代最大值元素应该最后出现。

冒泡排序是一种简单的算法,用于对一组给定的 n 个元素进行排序,这些元素以具有 n 个元素的数组的形式提供。冒泡排序将所有元素一一比较,并根据它们的值对它们进行排序。

实施步骤:

  1. 创建一个主窗口
  2. 用黑色填充主窗口
  3. 创建一个方法来显示在它们之间有特定间隙的条形列表
  4. 获取用户输入的键
  5. 如果按下空格键启动排序过程
  6. 对列表执行冒泡排序算法
  7. 每次内部迭代后,用黑色填充屏幕并调用 show 方法以条形的形式显示迭代列表。

下面是实现

# importing pygame
import pygame

pygame.init()

# setting window size
win = pygame.display.set_mode((500, 400))

# setting title to the window
pygame.display.set_caption("Bubble sort")

# initial position
x = 40
y = 40

# width of each bar
width = 20

# height of each bar (data to be sorted)
height = [200, 50, 130, 90, 250, 61, 110,
			88, 33, 80, 70, 159, 180, 20]

run = True

# method to show the list of height
def show(height):

	# loop to iterate each item of list
	for i in range(len(height)):

		# drawing each bar with respective gap
		pygame.draw.rect(win, (255, 0, 0), (x + 30 * i, y, width, height[i]))

# infinite loop
while run:

	# execute flag to start sorting
	execute = False

	# time delay
	pygame.time.delay(10)

	# getting keys pressed
	keys = pygame.key.get_pressed()

	# iterating events
	for event in pygame.event.get():

		# if event is to quit
		if event.type == pygame.QUIT:

			# making run = false so break the while loop
			run = False

	# if space bar is pressed
	if keys[pygame.K_SPACE]:
		# make execute flag to true
		execute = True

	# checking if execute flag is false
	if execute == False:

		# fill the window with black color
		win.fill((0, 0, 0))

		# call the height method to show the list items
		show(height)

		# update the window
		pygame.display.update()

	# if execute flag is true
	else:

		# start sorting using bubble sort technique
		for i in range(len(height) - 1):

			# after this iteration max element will come at last
			for j in range(len(height) - i - 1):

				# starting is greater then next element
				if height[j] > height[j + 1]:

					# save it in temporary variable
					# and swap them using temporary variable
					t = height[j]
					height[j] = height[j + 1]
					height[j + 1] = t

				# fill the window with black color
				win.fill((0, 0, 0))

				# call show method to display the list items
				show(height)

				# create a time delay
				pygame.time.delay(50)

				# update the display
				pygame.display.update()

# exiting the main window
pygame.quit()

输出 :

转载请注明:文章转载自 www.wk8.com.cn
本文地址:https://www.wk8.com.cn/it/1038157.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 wk8.com.cn

ICP备案号:晋ICP备2021003244-6号