In [1]:
import ipytracer
from IPython.display import display
Insertion sort is a simple sorting algorithm that builds the final sorted array (or list) one item at a time. It is much less efficient on large lists than more advanced algorithms such as quicksort, heapsort, or merge sort.
In [6]:
def insertion_sort(unsorted_list):
x = ipytracer.List1DTracer(unsorted_list)
display(x)
for i in range(1, len(x)):
j = i - 1
key = x[i]
while x[j] > key and j >= 0:
x[j+1] = x[j]
j = j - 1
x[j+1] = key
return x.data
In [7]:
insertion_sort([6,4,7,9,3,5,1,8,2])
Out[7]:
In [8]:
def insertion_sort(unsorted_list):
x = ipytracer.ChartTracer(unsorted_list)
display(x)
for i in range(1, len(x)):
j = i - 1
key = x[i]
while x[j] > key and j >= 0:
x[j+1] = x[j]
j = j - 1
x[j+1] = key
return x.data
In [9]:
insertion_sort([6,4,7,9,3,5,1,8,2])
Out[9]: