需要帮助实现可视化工具以与pygame进行合并排序

问题描述

我目前正在使用pygame构建排序可视化程序,到目前为止,我已经能够进行冒泡和选择排序。我目前正在做的是每次更改都绘制一个数组框架,这适用于气泡和选择排序。但是对于合并排序,总会有一些数组被拆分并合并回去,所以我无法在每一帧绘制该数组,因为只有一部分数组会显示每一帧。我目前仍停留在如何在合并排序上实现可视化工具的方面,下面我将举一个示例说明如何对冒泡排序进行操作,以及我目前对合并排序有什么了解。

# Bubble sort
def bubble_sort_visual(array,window,delay):
for i in range(len(array)):
    for j in range(0,len(array)-i-1):
        if array[j] > array[j + 1]:
            temp = array[j]
            array[j] = array[j + 1]
            array[j + 1] = temp
            pygame.draw.rect(screen,RED,(15 + 15*j,10,temp))
            pygame.display.update()

        # This block of code is what I use to show the array on screen each frame
        window.fill(GREEN)
        array_bars(heights,screen,WHITE) # drawing the array each frame
        pygame.time.delay(delay)
        pygame.display.update()


 # Merge sort
 def merge_sort_visual(array,delay):
 if len(array) > 1:
    mid = len(array) // 2
    left_array = array[:mid]
    right_array = array[mid:]

    merge_sort_visual(left_array,8)
    merge_sort_visual(right_array,8)

    left_index = 0
    right_index = 0
    sort_index = 0

    while left_index < len(left_array) and right_index < len(right_array):
        if left_array[left_index] <= right_array[right_index]:
            array[sort_index] = left_array[left_index]
            left_index += 1

        else:
            array[sort_index] = right_array[right_index]
            right_index += 1

        sort_index += 1

    while left_index < len(left_array):
        array[sort_index] = left_array[left_index]
        left_index += 1
        sort_index += 1

    while right_index < len(right_array):
        array[sort_index] = right_array[right_index]
        right_index += 1
        sort_index += 1

如上所述,我不确定将放入冒泡排序中的代码块放在合并排序中的位置,我尝试了一下,但是每次得到错误的结果。任何帮助将不胜感激,谢谢。

解决方法

有了气泡,您只需要处理一个数组。通过合并排序,您可以处理递归和多层数组。更新主数组是一个挑战,因为递归的每一层都只能看到整个数组的一部分。

解决方案是将部分数组的位置传递给子进程,以便子进程知道要更新整个数组的哪一部分。

下面是更新的代码来说明这个想法:

 # Merge sort
 def merge_sort_visual(start,array,window,delay):  # pass the starting postion of this array within the full array (first call is 0)
 if len(array) > 1:
        mid = len(array) // 2
        left_array = array[:mid]
        right_array = array[mid:]

        # This block of code is what I use to show the array on screen each frame
        window.fill(GREEN) 
        # for this method,you will need to create a temporary copy of the full array to display on the screen 
        array_bars(start,heights,screen,WHITE) # update part of the full array on screen (start location and array length)
        pygame.time.delay(delay)
        pygame.display.update()

        merge_sort_visual(start,left_array,8)  # pass location within full array
        merge_sort_visual(start+mid,right_array,8)  # pass location within full array