首页 > 解决方案 > 我想使用 pygame 在 python 中创建一个合并排序可视化器。代码没有给出正确的结果

问题描述

我正在创建一个排序可视化器,但代码没有打印正确的输出。我是 python 新手,所以这可能是一个愚蠢的错误,但我想不通也许问题在于在合并函数中创建 List L 和 R ...

import pygame
import random

pygame.init()
screen = pygame.display.set_mode((1000, 700))
pygame.display.set_caption("SORTING VISUALS")


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 merge(l, m, r):
    global rect, n
    n1 = m - l + 1
    n2 = r - m
    # create temp arrays
    L = []
    R = []
    # Copy data to temp arrays L[] and R[]
    for i in range(n1):
        L.append(Rect(rect[l + 1].X, rect[l + 1].Y, rect[l + 1].width, rect[l + 1].height))
    refresh()
    for j in range(n2):
        R.append(Rect(rect[m + 1 + j].X, rect[m + 1 + j].Y, rect[m + 1 + j].width, rect[m + 1 + j].height))
    refresh()
    i = 0 
    j = 0  
    k = l  

    while i < n1 and j < n2:
        print("checking merge...")
        if L[i].height <= R[j].height:
            # rect[k] = Rect(L[i].X, L[i].Y, L[i].width, L[i].height)
            rect[k], L[i] = L[i], rect[k]
            rect[k].X, L[i].X = L[i].X, rect[k].X
            i += 1
        else:
            # rect[k] = Rect(R[j].X, R[j].Y, R[j].width, R[j].height)
            rect[k], R[j] = R[j], rect[k]
            rect[k].X, R[j].X = R[j].X, rect[k].X
            j += 1
        k += 1
        for a in range(n):
            print(rect[a].height, end=" ")
        print()
    refresh()
    # Copy the remaining elements of L[], if there
    # are any
    while i < n1:
        rect[k], L[i] = L[i], rect[k]
        rect[k].X, L[i].X = L[i].X, rect[k].X
        i += 1
        k += 1
    refresh()
    # Copy the remaining elements of R[], if there
    # are any
    while j < n2:
        rect[k], R[j] = R[j], rect[k]
        rect[k].X, R[j].X = R[j].X, rect[k].X
        j += 1
        k += 1
    refresh()

我知道代码很可疑,但任何帮助都会很棒...您还可以提出一些优化建议...。

这个输出来了... 我的代码输出:

标签: pythonpygamemergesort

解决方案


有一条线显然是错误的。创建列表时,列表中R源元素的索引而不是:rectl + il + 1

L.append(Rect(rect[l + 1].X, rect[l + 1].Y, rect[l + 1].width, rect[l + 1].height))

for i in range(n1):
    L.append(Rect(rect[l + i].X, rect[l + i].Y, rect[l + i].width, rect[l + i].height))

推荐阅读