当前位置:首页python > 正文

python写的树形选择排序动态演示程序

作者:野牛程序员:2023-03-02 09:29:55python阅读 2691

在同一个窗口中刷新数据,可以将 fig, ax = plt.subplots() 这一行代码移到主函数中,在主函数中创建一个图形窗口并传递给 tree_selection_sort() 函数。

tree_selection_sort() 函数中,需要将 ax 参数添加到函数定义中,并将创建图形窗口的代码删除。然后,在排序过程中,可以使用 ax.clear() 方法清除图形窗口并重新绘制排序后的数据。

这个代码将创建一个图形窗口,显示未排序的数据,然后在同一个窗口中进行排序,并实时更新图表以显示排序过程。最后,它将打印出排序后的数据,并保持图形窗口打开以便查看结果。


import matplotlib.pyplot as plt
import random


def tree_selection_sort(data, ax):
    n = len(data)
    sorted_idx = n - 1
    while sorted_idx > 0:
        max_idx = 0
        for i in range(1, sorted_idx+1):
            if data[i] > data[max_idx]:
                max_idx = i

        data[max_idx], data[sorted_idx] = data[sorted_idx], data[max_idx]

        # Update the plot
        color = ['b'] * len(data)
        color[max_idx] = 'r'
        color[sorted_idx] = 'g'
        ax.clear()
        ax.bar(range(len(data)), data, color=color)
        ax.set_xlim(0, len(data))
        ax.set_ylim(0, max(data) + 10)
        for k in range(len(data)):
            ax.text(k, data[k] + 1, data[k], horizontalalignment='center', fontweight='bold', color='black')
        ax.text(max_idx, data[max_idx] + 5, str(data[max_idx]), horizontalalignment='center', fontweight='bold', color='white')
        ax.text(sorted_idx, data[sorted_idx] + 5, str(data[sorted_idx]), horizontalalignment='center', fontweight='bold', color='white')
        plt.pause(3)

        sorted_idx -= 1


if __name__ == '__main__':
    # Generate random data
    data = [random.randint(0, 100) for _ in range(10)]
    print('Unsorted data:', data)

    # Create a figure window
    fig, ax = plt.subplots()
    ax.set_xlim(0, len(data))
    ax.set_ylim(0, max(data) + 10)
    plt.title('Tree Selection Sort')

    # Sort the data using tree selection sort
    tree_selection_sort(data, ax)

    # Show the final sorted data
    print('Sorted data:', data)

    # Keep the plot window open
    plt.show()


下面这个代码,每趟排序都会生成新的窗体,不利于观察:

import matplotlib.pyplot as plt
import random


def tree_selection_sort(data):
    n = len(data)
    sorted_idx = n - 1
    while sorted_idx > 0:
        max_idx = 0
        for i in range(1, sorted_idx+1):
            if data[i] > data[max_idx]:
                max_idx = i

        data[max_idx], data[sorted_idx] = data[sorted_idx], data[max_idx]

        # plot the sorting process
        fig, ax = plt.subplots()
        ax.bar(range(len(data)), data)
        ax.set_xlim(0, len(data))
        ax.set_ylim(0, max(data) + 10)
        plt.title('Tree Selection Sort')
        plt.show(block=False)

        color = ['b'] * len(data)
        color[max_idx] = 'r'
        color[sorted_idx] = 'g'
        ax.clear()
        ax.bar(range(len(data)), data, color=color)
        ax.set_xlim(0, len(data))
        ax.set_ylim(0, max(data) + 10)
        plt.title('Tree Selection Sort')
        for k in range(len(data)):
            plt.text(k, data[k] + 1, data[k], horizontalalignment='center', fontweight='bold', color='black')
        plt.text(max_idx, data[max_idx] + 5, str(data[max_idx]), horizontalalignment='center', fontweight='bold', color='white')
        plt.text(sorted_idx, data[sorted_idx] + 5, str(data[sorted_idx]), horizontalalignment='center', fontweight='bold', color='white')
        plt.pause(1)

        sorted_idx -= 1


if __name__ == '__main__':
    # Generate random data
    data = [random.randint(0, 100) for _ in range(10)]
    print('Unsorted data:', data)

    # Sort the data using tree selection sort
    tree_selection_sort(data)

    print('Sorted data:', data)


野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892
野牛程序员教少儿编程与信息学竞赛-微信|电话:15892516892
相关推荐

最新推荐

热门点击