我想制作一个排序可视化工具,排序有效但可视化工具没有

I want to make a sorting Visualizer, the sort works but visualizer doesnot

正如标题所说,我想用 python 和 pygame 创建一个可视化的冒泡排序。排序工作完美,但在可视化时它永远不会得到正确的输出。

排序完美,但屏幕栏没有交换。 我还添加了一些颜色以更好地理解代码...

代码:-

import pygame
import random

WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)

L = []
rect = []
n = 10  # n belongs till [50,220]
WidthOfEachBar = 800 // (n + 1)


class Rect:
    def __init__(self, x, y, width, height):
        self.X = x
        self.Y = y
        self.width = width
        self.height = height
        self.colour = BLACK

    def show(self):
        pygame.draw.rect(screen, self.colour, (self.X, self.Y, self.width, self.height))

    def changeCol(self, colour):
        self.colour = colour


def array(n_):
    global L
    arr = [(3 * i) for i in range(1, n_ + 1)]
    for a in range(n_):
        random_no = random.choice(arr)
        L.append(random_no + 10)
        arr.remove(random_no)


array(n)

for i in range(n):
    x = 50 + (i + 1) * (1 + WidthOfEachBar)
    y = 680 - L[i]
    rect.append(Rect(x, y, WidthOfEachBar, L[i]))


def swap(a, b):
    global rect
    rect[a], rect[b] = rect[b], rect[a]


def bubble_sort():
    global n, rect
    for ii1 in range(n):
        for j in range(n - 1):
            rect[j].colour = GREEN
            rect[j + 1].colour = GREEN

            if rect[j].height > rect[j + 1].height:
                # print(r[j].X, r[j + 1].X)
                swap(j, j + 1)
                # print(r[j].X, r[j + 1].X)
                for amb in range(n):
                    print(rect[amb].height, end=" ")
                print()
            screen.fill(WHITE)
            for no1 in range(n):
                rect[no1].show()
            pygame.time.delay(0)
            pygame.display.update()
            rect[j].colour = BLACK
            rect[j + 1].colour = BLACK


pygame.init()
screen = pygame.display.set_mode((1000, 700))
pygame.display.set_caption("SORTING VISUALS")
is_sorted = False
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    screen.fill(WHITE)
    if not is_sorted:
        bubble_sort()
    pygame.display.update()

这里的画面每次都会更新,但是我没看懂问题所在。 代码很可疑,我知道,但任何帮助都会很棒

您的代码中的问题是您正在交换列表中的元素,但相应的矩形没有改变它们的位置。您应该更改 swap 函数:

def swap(a, b):
    global rect
    rect[a], rect[b] = rect[b], rect[a]
    rect[a].X, rect[b].X = rect[b].X, rect[a].X

现在这将交换列表中的元素以及交换它们对应矩形的位置。