[PYTHON] visualize insertion sort

import random

def vs_insertion(l, i):
    n = l.copy()
    n.insert(i+1, "*")
    n.insert(i+1, "]")
    n.insert(0, "[")
    print(" ".join(map(lambda x: str(x), n)))


def insertion_sort(l):
    size = len(l)
    i = 1
    while i < size:
        tmp = l[i]
        j = i - 1
        while j >= 0 and tmp < l[j]:
            l[j + 1] = l[j]
            j -= 1
        l[j + 1] = tmp
        vs_insertion(l, i)
        i += 1


r = [random.choice([i for i in range(1000)]) for r in range(10)]
insertion_sort(r)
print(r)

Output

[ 169 170 ] * 579 477 707 108 884 393 172 447
[ 169 170 579 ] * 477 707 108 884 393 172 447
[ 169 170 477 579 ] * 707 108 884 393 172 447
[ 169 170 477 579 707 ] * 108 884 393 172 447
[ 108 169 170 477 579 707 ] * 884 393 172 447
[ 108 169 170 477 579 707 884 ] * 393 172 447
[ 108 169 170 393 477 579 707 884 ] * 172 447
[ 108 169 170 172 393 477 579 707 884 ] * 447
[ 108 169 170 172 393 447 477 579 707 884 ] *
[108, 169, 170, 172, 393, 447, 477, 579, 707, 884]

ref: http://www.geocities.jp/m_hiroi/light/python02.html

Recommended Posts

visualize insertion sort
Insertion sort
Insertion sort implementation
Insertion sort of AOJ exercises
sort
Selection Sort
[Python] Sort
Natural sort
Python # sort
Bubble sort
Bubble sort
Algorithm learned with Python 16th: Sorting (insertion sort)