📅  最后修改于: 2023-12-03 15:10:10.417000             🧑  作者: Mango
堆排序是一种高效的排序算法,其时间复杂度为O(nlogn)。它的基本思路是将待排序的序列构建成一个完全二叉树,将该二叉树调整为大根堆或小根堆,然后不断地将堆顶元素与堆底元素交换,并重新调整堆,直到排序完成。
以下是使用Python实现的堆排序可视化程序。
import pygame
import random
WIDTH = 800
HEIGHT = 600
FPS = 60
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
SIZE = 100
NUMBERS = [random.randint(0, HEIGHT) for _ in range(SIZE)]
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Heap Sort Visualization")
clock = pygame.time.Clock()
def draw(numbers, states):
screen.fill(WHITE)
spacing = WIDTH // len(numbers)
for i in range(len(numbers)):
rect = pygame.Rect(i * spacing + 1, HEIGHT - numbers[i], spacing - 1, numbers[i])
pygame.draw.rect(screen, states[i], rect)
pygame.display.flip()
def heapify(numbers, n, i):
largest = i
left = 2 * i + 1
right = 2 * i + 2
if left < n and numbers[largest] < numbers[left]:
largest = left
if right < n and numbers[largest] < numbers[right]:
largest = right
if largest != i:
states = [WHITE] * SIZE
states[i] = BLUE
states[largest] = BLUE
draw(numbers, states)
numbers[i], numbers[largest] = numbers[largest], numbers[i]
heapify(numbers, n, largest)
def heapsort(numbers):
n = len(numbers)
for i in range(n, -1, -1):
heapify(numbers, n, i)
states = [GREEN if j < i else WHITE for j in range(SIZE)]
draw(numbers, states)
for i in range(n - 1, 0, -1):
numbers[0], numbers[i] = numbers[i], numbers[0]
states = [RED if j == i else WHITE for j in range(SIZE)]
draw(numbers, states)
heapify(numbers, i, 0)
heapsort(NUMBERS)
running = True
while running:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.quit()
在这个程序中,我们使用Pygame库绘制了一个可视化窗口来显示算法的过程。程序首先生成了一个包含100个随机数的列表,然后将列表传递给排序函数。排序函数heapsort(numbers)
以三个参数调用heapify(numbers, n, i)
函数,参数numbers
是被排序的列表,参数n
是实例化堆的大小,参数i
是父节点的编号。heapify(numbers, n, i)
函数是一个递归函数,从上到下调整局部堆,将堆顶元素与对应子树的最大元素交换。最后,当局部堆已被准确安排时,调用堆排序堆整个列表。算法成功排序后,屏幕将以绿色/绿色突出显示已排序的数字。