LoginSignup
1
1

More than 5 years have passed since last update.

visualize insertion sort

Last updated at Posted at 2016-01-08
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

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1