插入排序輸出到console帶顏色字體展示插入時(shí)數(shù)據(jù)交換
圖片
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
動(dòng)態(tài)顯示插入動(dòng)作代碼
# 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):
"""生成隨機(jī)列表"""
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\rq79ladc".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口打印排序時(shí)候數(shù)據(jù)的移位"""
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)