In Insertion Sort Part 1, you inserted one element into an array at its correct sorted position. Using the same approach repeatedly, can you sort an entire array?

Guideline: You already can place an element into a sorted array. How can you use that code to build up a sorted array, one element at a time? Note that in the first step, when you consider an array with just the first element, it is already sorted since there's nothing to compare it to.

In this challenge, print the array after each iteration of the insertion sort, i.e., whenever the next element has been inserted at its correct position.  Since the array composed of just the first element is already sorted, begin printing after placing the second element.

Example. 

$n=7$ 

$arr=[3,4,7,5,6,2,1]$   

Working from left to right, we get the following output:

3 4 7 5 6 2 1
3 4 7 5 6 2 1
3 4 5 7 6 2 1
3 4 5 6 7 2 1
2 3 4 5 6 7 1
1 2 3 4 5 6 7

Function Description

Complete the insertionSort2 function in the editor below.  

insertionSort2 has the following parameter(s):  

int n: the length of $\textbf{arr}$  
int arr[n]: an array of integers  

Prints  

At each iteration, print the array as space-separated integers on its own line.  

Input Format

The first line contains an integer, $n$, the size of $\textbf{arr}$. 

 The next line contains $n$ space-separated integers $arr\left[i\right]$.  

Constraints

$1\leq n\leq1000$ 

$-10000\leq arr[i]\leq10000,0\leq i\lt n$ 

Output Format

Print the entire array on a new line at every iteration.

Sample Input
STDIN           Function
-----           --------
6               n = 6
1 4 3 5 6 2     arr = [1, 4, 3, 5, 6, 2]

Sample Output
1 4 3 5 6 2 
1 3 4 5 6 2 
1 3 4 5 6 2 
1 3 4 5 6 2 
1 2 3 4 5 6 

Explanation

Skip testing $\mbox{1}$ against itself at position $\mbox{0}$.  It is sorted. 

Test position $\mbox{1}$ against position $\mbox{0}$: $4>1$, no more to check, no change. 

Print $\textbf{arr}$ 

Test position $2$ against positions $\mbox{1}$ and $\mbox{0}$: 

$3<4$, new position may be $\mbox{1}$.  Keep checking.    
$3>1$, so insert $3$ at position $\mbox{1}$ and move others to the right.   

Print $\textbf{arr}$ 

Test position $3$ against positions $2,1,0$ (as necessary): no change. 

Print $\textbf{arr}$ 

Test position $\begin{array}{c}4\end{array}$ against positions $3,2,1,0$: no change. 

Print $\textbf{arr}$ 

Test position $5$ against positions $4,3,2,1,0$, insert $2$ at position $\mbox{1}$ and move others to the right. 

Print $\textbf{arr}$

Difficulty: EASY

Solutions:
size = int(input())
array = input().split(' ')
arr = ['None'] * size
for i in range(size):
	arr[i] = int(array[i])
i = 1
while i < size:
	tmp = arr[i]
	j = i - 1
	while arr[j] > tmp and j > -1:
		arr[j + 1] = arr[j]
		j = j - 1
	arr[j + 1] = tmp
	for k in range(size):
		print(arr[k], end=' ')
	print()
	i = i + 1


import sys

def insertionSort(ar):
	output = ''
	i = 1
	done = False
	ar[0] = int(ar[0])
	while i < len(ar):
		done = False
		toInsert = int(ar.pop(i))
		j = 0
		while j < i and (not done):
			if ar[j] > toInsert:
				ar.insert(j, toInsert)
				done = True
			j += 1
		if not done and j != len(ar):
			ar.insert(j, toInsert)
		elif not done:
			ar.append(toInsert)
		i += 1
		for val in ar:
			output += str(int(val)) + ' '
		output += '\n'
	return output.strip()
length = int(sys.stdin.readline())
array = sys.stdin.readline().split(' ')
print(insertionSort(array[0:length]))


import sys

def display(array):
	[print(x, end=' ') for x in array]
	print()
N = int(sys.stdin.readline())
array = [int(X) for X in sys.stdin.readline().split()]
for i in range(1, N):
	num = array[i]
	for j in range(i - 1, -1, -1):
		if array[j] > num and j != 0:
			array[j + 1] = array[j]
		elif array[j] > num and j == 0:
			array[j + 1] = array[j]
			array[j] = num
		else:
			array[j + 1] = num
			break
	display(array)


x = int(input())
a = input().split()
if x == 1:
	print(a[0])
j = 1
while j < x:
	i = j
	v = int(a[i])
	while i > 0:
		t1 = int(a[i - 1])
		if t1 > v:
			a[i] = t1
			a[i - 1] = v
		i -= 1
	for num in a:
		print(num, end=' ')
	print()
	j += 1


def insertionSort(ar):
	x = len(ar)
	v = ar[x - 1]
	j = x - 2
	finarr = []
	while ar[j] > v:
		j = j - 1
	for k in range(0, j + 1):
		finarr.append(ar[k])
		print(ar[k], end=' ')
	finarr.append(v)
	print(v, end=' ')
	for k in range(j + 2, x):
		finarr.append(ar[k - 1])
		print(ar[k - 1], end=' ')
	return finarr
n = int(input(''))
elem = input('')
numbers = elem.split()
arr = []
newarr = []
for i in range(0, n):
	arr.append(int(numbers[i]))
newarr.append(arr[0])
for i in range(1, n):
	newarr.append(arr[i])
	newarr = insertionSort(newarr)
	for j in range(i + 1, n):
		print(arr[j], end=' ')
	print('')


l = int(input())
ar = input().split()
for size in range(l):
	ar[size] = int(ar[size])

def shift(plist, index):
	temp = plist[index]
	if plist[index - 1] > plist[index]:
		plist[index] = plist[index - 1]
		plist[index - 1] = temp
		if index - 2 == -1:
			pass
		else:
			shift(plist, index - 1)
	return plist
for listing in range(1, l):
	string = ''
	ar = shift(ar, listing)
	for size2 in range(l):
		string = string + str(ar[size2]) + ' '
	print(string)


import sys

def print_ar(a):
	for i in a:
		print(i, end=' ')
	print('')

def insert_key(n, ar):
	key = ar[n - 1]
	k = n - 1
	for i in range(n - 2, -1, -1):
		if key < ar[i]:
			ar[i + 1] = ar[i]
			k = k - 1
		else:
			break
	ar[k] = key
	print_ar(ar)
n = int(sys.stdin.readline())
raw = sys.stdin.readline().split()
ar = []
for i in raw:
	ar.append(int(i))
if n < 2:
	print_ar(ar)
else:
	for i in range(2, n + 1):
		insert_key(i, ar)


import sys

def insertionSort(startIdx, a, t):
	for idx in range(startIdx, 0, -1):
		if a[idx] < a[idx - 1]:
			(a[idx - 1], a[idx]) = (a[idx], a[idx - 1])
		elif a[idx] >= a[idx - 1]:
			break
	for x in a:
		sys.stdout.write('{} '.format(x))
	sys.stdout.write('\n')
t = int(input())
a = list(map(int, sys.stdin.readline().split()))
for i in range(1, t):
	insertionSort(i, a, t)


import sys
x = int(input())
number = input()
s = [int(s) for s in number.split()]
for i in range(1, len(s)):
	val = s[i]
	j = i - 1
	while j >= 0 and s[j] > val:
		s[j + 1] = s[j]
		j = j - 1
	s[j + 1] = val
	for i in range(0, x):
		print(s[i], end=' ')
	print()


import pdb

def display(ar):
	for i in ar:
		print(i, end=' ')
	print()

def insertionSort(ar):
	for i in range(1, len(ar)):
		if ar[i] > ar[i - 1]:
			display(ar)
			continue
		else:
			v = ar[i]
			index = i
			while ar[index - 1] > v:
				ar[index] = ar[index - 1]
				index -= 1
				if index == 0:
					break
			ar[index] = v
			display(ar)
n = int(input())
temp = input().split(' ')
ar = []
for i in temp:
	ar.append(int(i))
insertionSort(ar)


N = int(input())
myList = [int(x) for x in input().split()]

def myInsert(myList, num):
	j = 0
	while num > myList[j]:
		j += 1
	myList.insert(j, num)
	return myList
for i in range(1, N):
	if not myList[i - 1] < myList[i]:
		temp = myList[i]
		del myList[i]
		myInsert(myList, temp)
	for x in myList:
		print(x, end=' ')
	print()


def printArr(arr):
	for i in range(len(arr)):
		print(arr[i], end=' ')
size = int(input())
arr = input().strip().split()
arr = [int(entry) for entry in arr]
for i in range(1, size):
	key = arr[i]
	j = i - 1
	while j >= 0 and arr[j] > key:
		arr[j + 1] = arr[j]
		j -= 1
	arr[j + 1] = key
	printArr(arr)
	print()


l = []
n = int(input())
l = input().split(' ')
for i in range(0, n):
	l[i] = int(l[i])

def P():
	for j in range(0, n):
		print('%d ' % l[j], end='')
	print()
for i in range(1, n):
	j = i - 1
	x = l[i]
	while (j >= 0) & (x < l[j]):
		l[j + 1] = l[j]
		j = j - 1
	l[j + 1] = x
	P()


import sys

def insertionSort():
	arlen = int(sys.stdin.readline())
	temp_ar = sys.stdin.readline().split()
	ar = []
	for a in temp_ar:
		ar.append(int(a))
	i = 1
	switch = False
	while i < len(ar):
		j = i
		switch = False
		while ar[j] < ar[j - 1] and j > 0:
			(ar[j], ar[j - 1]) = (ar[j - 1], ar[j])
			switch = True
			j -= 1
		i += 1
		for num in ar:
			print(num, '', end='')
			if ar.index(num) == len(ar) - 1:
				print()
insertionSort()


def insertionSort(ar):
	l = len(ar)
	val = ar[l - 1]
	srt = False
	N = l - 1
	while not srt:
		if N == 0 or val > ar[N - 1]:
			ar[N] = val
			srt = True
		else:
			ar[N] = ar[N - 1]
		N = N - 1
	return ar
N = int(input())
ar = [int(x, 10) for x in input().split()]
for i in range(2, N + 1):
	ar = insertionSort(ar[:i]) + ar[i:]
	for x in ar:
		print(x, end=' ')
	print()


import sys

def printList(ar):
	a = ''
	for i in ar:
		a += str(i) + ' '
	print(a)

def insertionSort(n, ar):
	for i in range(1, n):
		V = ar.pop(i)
		for j in range(i):
			if ar[j] > V:
				ar.insert(j, V)
				break
		if len(ar) < n:
			ar.insert(i, V)
		printList(ar)
n = int(input())
ar = list(map(int, input().split()))
insertionSort(n, ar)


def printArr(arr):
	for elt in arr:
		print(elt, end=' ')
	print()
n = int(input())
args = [int(i) for i in input().split()]
for i in range(1, n):
	if args[i] < args[i - 1]:
		toInsert = args[i]
		for j in range(i, 0, -1):
			if args[j - 1] > toInsert:
				args[j] = args[j - 1]
			else:
				args[j] = toInsert
				break
			if j == 1 and toInsert < args[j]:
				args[0] = toInsert
	printArr(args)


N = int(input())
array = list(map(int, input().split()))

def insertionSort(ar):
	for i in range(N):
		j = i
		while j > 0 and ar[j - 1] > ar[j]:
			(ar[j], ar[j - 1]) = (ar[j - 1], ar[j])
			j -= 1
		if i > 0:
			printArray(ar)

def printArray(array):
	for i in array:
		print(i, end=' ')
	print('')
insertionSort(array)


def insertionSort(ar):
	n = len(ar)
	for i in range(1, n):
		v = ar[i]
		for j in range(i, 0, -1):
			if ar[j - 1] > v:
				ar[j] = ar[j - 1]
			else:
				ar[j] = v
				break
		if v < ar[0]:
			ar[0] = v
		print_array(ar)

def print_array(ar):
	result = ''
	for el in ar:
		result += str(el) + ' '
	result += ''
	print(result)
m = input()
ar = [int(i) for i in input().strip().split()]
insertionSort(ar)


def printAr(ar):
	for j in ar:
		print(j, end=' ')
	print()

def insert(ar, n):
	a = ar[n - 1]
	for i in range(n - 2, -1, -1):
		if ar[i] > a:
			ar[i + 1] = ar[i]
		else:
			ar[i + 1] = a
			break
	else:
		ar[0] = a
	return ar
n = int(input())
ar = [int(num) for num in input().split()]
for i in range(2, n + 1):
	ar = insert(ar[:i], i) + ar[i:]
	printAr(ar)


cases = int(input())
array = list()
i = 0
temp = ''
temp = input()
array = temp.split()
while i < cases:
	array[i] = int(array[i])
	i = i + 1
lenArray = len(array)
counter = 0
i = 1
while i < lenArray:
	j = i
	while j > 0 and array[j - 1] > array[j]:
		array[j - 1] = array[j - 1] + array[j]
		array[j] = array[j - 1] - array[j]
		array[j - 1] = array[j - 1] - array[j]
		counter = counter + 1
		j = j - 1
	outStr = ''
	for element in array:
		outStr = outStr + str(element) + ' '
	print(outStr)
	i = i + 1


def insert(eli, i, arr):
	if i == eli:
		pass
	elif arr[eli] < arr[i]:
		buf = arr[i]
		arr[i] = arr[eli]
		for j in range(i + 1, eli + 1):
			buf2 = arr[j]
			arr[j] = buf
			buf = buf2
	else:
		insert(eli, i + 1, arr)

def pprint(arr):
	out = ''
	for i in range(len(arr)):
		out = out + str(arr[i]) + ' '
	print(out)
input()
arr = [int(x) for x in input().split()]
for i in range(1, len(arr)):
	insert(i, 0, arr)
	pprint(arr)


import sys

def print_list(data):
	for element in data:
		print(element, end=' ')
	print()
length = int(sys.stdin.readline())
data = []
raw = sys.stdin.readline().split()
for index in range(length):
	data.append(int(raw[index]))
for index in range(1, length):
	element = data[index]
	try:
		for pointer in range(index, 0, -1):
			if data[pointer - 1] < element:
				raise StopIteration('Place found!')
			data[pointer] = data[pointer - 1]
		data[0] = element
	except StopIteration:
		data[pointer] = element
	print_list(data)


n = int(input())
array = [int(val) for val in input().split()]
for i in range(1, n):
	item = array[i]
	j = i
	while j > 0 and array[j - 1] > item:
		array[j] = array[j - 1]
		j -= 1
	array[j] = item
	[print(val, end=' ') for val in array]
	print()


def insert_sort(N):
	if len(N) == 1:
		return N
	for i in range(1, len(N)):
		k = N[i]
		j = i
		while j > 0 and N[j - 1] > k:
			N[j] = N[j - 1]
			j -= 1
		N[j] = k
		for l in N:
			print(l, end=' ')
		print('\r')
num = int(input())
ar = [int(c) for c in input().split()]
insert_sort(ar)


s = int(input())
iarr = [int(x) for x in input().split(' ')]

def printArr(arr):
	op = ''
	for x in arr:
		op = op + str(x) + ' '
	print(op)

def insert(arr):
	s = len(arr)
	v = arr[s - 1]
	for i in range(s - 2, -1, -1):
		if arr[i] > v:
			arr[i + 1] = arr[i]
			if i == 0:
				arr[0] = v
		else:
			arr[i + 1] = v
			break
	return arr
for e in range(1, s):
	iarr[:e + 1] = insert(iarr[:e + 1])
	printArr(iarr)