📜  使用Python可视化冒泡排序

📅  最后修改于: 2022-05-13 01:54:40.278000             🧑  作者: Mango

使用Python可视化冒泡排序

先决条件: Matplotlib 简介、PyQt5 简介、冒泡排序

学习任何算法都是很困难的,因为你在 GeekforGeeks,你肯定喜欢理解和实现各种算法。我们每个人第一次都很难理解算法。我们倾向于更多地理解那些被正确形象化的事物。我们开始的基本问题之一是排序算法。学习这些算法对您来说可能具有挑战性,因此我们今天向您展示如何将它们可视化。

需要的模块

Matplotlib: Matplotlib 是一个了不起的Python可视化库,用于数组的 2D 绘图。要安装它,请在终端中键入以下命令

pip install matplotlib

  PyQt5: PyQt5 是跨平台的 GUI 工具包,是 Qt v5 的一组Python绑定。由于该库提供的工具和简单性,人们可以非常轻松地开发交互式桌面应用程序。要安装它,请在终端中键入以下命令。

pip install PyQt5==5.9.2

因此,所有设置完成后,让我们开始实际编码。首先,创建一个名为main.py的文件并向其中添加以下代码行。

Python3
# imports
import random
from matplotlib import pyplot as plt, animation
  
# helper methods
def swap(A, i, j):
    A[i], A[j] = A[j], A[i]
  
  
# algorithms
def bubblesort(A):
    swapped = True
      
    for i in range(len(A) - 1):
        if not swapped:
            return
        swapped = False
          
        for j in range(len(A) - 1 - i):
            if A[j] > A[j + 1]:
                swap(A, j, j + 1)
                swapped = True
            yield A
  
  
def visualize():
    N = 30
    A = list(range(1, N + 1))
    random.shuffle(A)
      
    # creates a generator object containing all 
    # the states of the array while performing 
    # sorting algorithm
    generator = bubblesort(A)
      
    # creates a figure and subsequent subplots
    fig, ax = plt.subplots()
    ax.set_title("Bubble Sort O(n\N{SUPERSCRIPT TWO})")
    bar_sub = ax.bar(range(len(A)), A, align="edge")
      
    # sets the maximum limit for the x-axis
    ax.set_xlim(0, N)
    text = ax.text(0.02, 0.95, "", transform=ax.transAxes)
    iteration = [0]
      
    # helper function to update each frame in plot
    def update(A, rects, iteration):
        for rect, val in zip(rects, A):
            rect.set_height(val)
        iteration[0] += 1
        text.set_text(f"# of operations: {iteration[0]}")
  
    # creating animation object for rendering the iteration
    anim = animation.FuncAnimation(
        fig,
        func=update,
        fargs=(bar_sub, iteration),
        frames=generator,
        repeat=True,
        blit=False,
        interval=15,
        save_count=90000,
    )
      
    # for showing the animation on screen
    plt.show()
    plt.close()
  
  
if __name__ == "__main__":
    visualize()


输出: