插入排序输出到console带颜色字体展示插入时数据交换
图片
insert_sort.gif
插入排序算法
def sort_a(arr):
"""插入排序"""
arr = copy.deepcopy(arr)
for i, cursor in enumerate(arr):
pos = i
while pos > 0 and arr[pos - 1] > cursor:
arr[pos] = arr[pos - 1]
pos = pos - 1
arr[pos] = cursor
return arr
动态显示插入动作代码
# coding:utf-8
"""
author: Allen
datetime:
python version: 3.x
summary:
install package:
"""
from typing import List
import random
from colorama import Fore
import copy
class GenData(object):
def __init__(self):
pass
@staticmethod
def random_list(start: int = 0, end: int = 10, step: int = 1):
"""生成随机列表"""
seq = list(range(start, end, step))
random.shuffle(seq)
return seq
class ConsolePrint(object):
@staticmethod
def annotation_seq(seq: List, index: int):
"""带颜色打印字体"""
return ' '.join([Fore.RESET + str(d) if i != index else Fore.RED + str(d) for i, d in enumerate(seq)])
@staticmethod
def cover_print(data):
print("\r\r{d}".format(d=str(data).strip()), end='')
class InsertSort(object):
def __init__(self):
pass
@staticmethod
def sort_a(arr):
"""插入排序"""
arr = copy.deepcopy(arr)
for i, cursor in enumerate(arr):
pos = i
while pos > 0 and arr[pos - 1] > cursor:
arr[pos] = arr[pos - 1]
pos = pos - 1
arr[pos] = cursor
return arr
@staticmethod
def sort_a_draw(arr, sleep=1):
"""console口打印排序时候数据的移位"""
arr = copy.deepcopy(arr)
for i, cursor in enumerate(arr):
pos = i
InsertSort._annotation_p(arr, pos=pos, cursor=cursor)
while pos > 0 and arr[pos - 1] > cursor:
InsertSort._annotation_p(arr, pos=pos, cursor=cursor)
arr[pos] = arr[pos - 1]
InsertSort._annotation_p(arr, pos=pos, cursor=cursor)
pos = pos - 1
time.sleep(sleep)
InsertSort._annotation_p(arr, pos=pos, cursor=cursor)
arr[pos] = cursor
InsertSort._annotation_p(arr, pos=pos, cursor=cursor)
time.sleep(sleep)
return arr
@staticmethod
def _annotation_p(arr, pos, cursor):
tmp_arr = copy.deepcopy(arr)
tmp_arr[pos] = cursor
ConsolePrint.cover_print(ConsolePrint.annotation_seq(tmp_arr, index=pos))
if __name__ == '__main__':
seq = GenData.random_list()
res = InsertSort.sort_a_draw(seq)
网友评论