用 Python 实现排序算法可视化

· · 个人记录

前言

经常在孰知乎的时候看到很多关于排序算法效率的测试,一个一个竖条的排序看得惊心动魄。于是,打算用自己弱鸡的 Python 编程能力,实现一下排序算法可视化。

环境要求

def StartTimer(self): self.start_flag=True self.start = time.time()

def StopTimer(self): self.start_flag=False

def GetTime(self): if self.start_flag: self.time = time.time()-self.start

帧的间隔时间、排序方法、颜色主题设置传参

def SetTimeInterval(self, time_interval): self.time_interval=time_interval

def SetSortType(self, sort_title): self.sort_title=sort_title

def SetColorTheme(self, color_theme): self.color_theme=color_theme

随机生成数据

def Shuffle(self): random.shuffle(self.data)

接着,就可以用主程序对接到数据生成里
```python
from data import SortClass # 调用刚刚写好的类

def main():
    MAXLENGTH=1024
    Length=args.length if args.length<MAXLENGTH else MAXLENGTH
    Interval=args.interval
    SortType=args.sort_type
    Resampling=args.resample
    Sparse=args.sparse
    Record=args.record
    ColorTheme=args.color_theme
    try:
        SortMethod=eval(SortType)
    except:
        print("Sort Type Not Found! Please Check if %s Exists or Not!"%SortType)
        exit()

    sv=SortData(Length, time_interval=Interval, sort_title=SortType, is_resampling=Resampling, is_sparse=Sparse, record=Record, color_theme=ColorTheme) # 传参数给 data.py
    sv.Visualize()
    sv.StartTimer()
    SortMethod(sv)
    sv.StopTimer()
    sv.SetTimeInterval(0)
    sv.Visualize()

if __name__ == "__main__":
    main()

然后,回到 data.py 用 cv2 画画里

# 获取设置
def Getfigure(self):
        _bar_width = 5
        figure = np.full((self.length*_bar_width,self.length*_bar_width,3), 255,dtype=np.uint8)
        for i in range(self.length):
            val = self.data[i]
            figure[-1-val*_bar_width:, i*_bar_width:i*_bar_width+_bar_width] = self.GetColor(val, self.length, self.color_theme)
        self._bar_width = _bar_width
        self.figure = figure
        size = _bar_width*self.length
        self.im_size = size if size < self.MAX_IM_SIZE else self.MAX_IM_SIZE

@staticmethod
# 巧妙地做出渐变色
def GetColor(val, TOTAL, color_theme):
        if color_theme == "blue":
            return (100+val*255//(2*TOTAL), 257+val*255//(2*TOTAL), 0)
        if color_theme == "green":
            return (150-val*255//(2*TOTAL), 255-val*255//(2*TOTAL), 0)

def _set_figure(self, idx, val):
        min_col = idx*self._bar_width
        max_col = min_col+self._bar_width
        min_row = -1-val*self._bar_width
        self.figure[ : , min_col:max_col] = self.WHITE
        self.figure[ min_row: , min_col:max_col] = self.GetColor(val, self.length, self.color_theme)
def SetColor(self, img, marks, color):
        for idx in marks:
            min_col = idx*self._bar_width
            max_col = min_col+self._bar_width
            min_row = -1-self.data[idx]*self._bar_width
            img[min_row:, min_col:max_col] = color
def Mark(self, img, marks, color):
        self.SetColor(img, marks, color)
def SetVal(self, idx, val):
        self.data[idx] = val
        self._set_figure(idx, val)

        self.Visualize((idx,))

def Swap(self, idx1, idx2):
        self.data[idx1], self.data[idx2] = self.data[idx2], self.data[idx1]
        self._set_figure(idx1, self.data[idx1])
        self._set_figure(idx2, self.data[idx2])

        self.Visualize((idx1, idx2))
def Visualize(self, mark1= None, mark2=None):
        img = self.figure.copy()
        if mark2:
            self.Mark( img, mark2, self.YELLOW)
        if mark1:
            self.Mark( img, mark1, self.RED)

        # 画画
        img = cv2.resize(img, (self.im_size, self.im_size))

        # 屏幕上显示时间
        self.GetTime()
        cv2.putText(img, self.sort_title+" Time:%02.2fs"%self.time, (20,20), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, self.BLACK, 1)

        # 录制
        if self.record:
            self.vdo_wtr.write(img)

        # 显示文字和帧时间间隔
        cv2.imshow(self.sort_title, img)
        cv2.waitKey(self.time_interval)

这样呢,数据生成及其与主程序的对接就做完了 撒花????

排序算法对接

现在,我们要解决的是如何将排序算法对接 data.py 显示到屏幕上 有了以上的铺垫,这里实现就很简单了 我们以冒泡排序为例,算法代码如下

def BubbleSort(sv):
        # 检测一下数据有没有问题
        assert isinstance(sv, SortData), "Type Error"

        Length = sv.length
        for i in range(Length-1, -1, -1):
            for j in range(0, i, 1):
                if sv.data[j] > sv.data[j+1]:
                    sv.Swap(j, j+1)

然后与 data.py 再对接一下

from data import SortData

def BubbleSort(sv):
    assert isinstance(sv, SortData), "Type Error"

    Length = sv.length
    for i in range(Length-1, -1, -1):
        for j in range(0, i, 1):
            if sv.data[j] > sv.data[j+1]:
                sv.Swap(j, j+1)

if __name__ == "__main__":
    sv=SortData(64)
    sv.Visualize()
    sv.StartTimer()
    BubbleSort(sv)
    sv.StopTimer()
    sv.SetTimeInterval(0)
    sv.Visualize()

是不是很简单 qwq 桶排、快速排序等等对接方式与上面的都是一样的

小结

到此为止,所有的工作就已经完成了,小伙伴们可以 python main.py 试试哦! 以上呢,我们主要使用 cv2 完成了绘图,仅涉及了一些 Python 的基本知识,不太懂的小伙伴们可以去自学一下 Python 的类和函数,洛谷的这一篇 Python 30分钟入门指南 也是很不错的呢!

后记

所有的源代码,我已经整理到了 Github 仓库 里,大家可以去看看 顺便一说,我已经打包成了 pip模块,直接 pip install sortvis 就可以用了呢!