Sorting 

One common task for computers is to sort data. For example, people might want to see all their files on a computer sorted by size. Since sorting is a simple problem with many different possible solutions, it is often used to introduce the study of algorithms. 

Insertion Sort 

These challenges will cover Insertion Sort, a simple and intuitive sorting algorithm. We will first start with a nearly sorted list.

Insert element into sorted list 

Given a sorted list with an unsorted number $\boldsymbol{\mathrm{~e~}}$ in the rightmost cell, can you write some simple code to insert $\boldsymbol{\mathrm{~e~}}$ into the array so that it remains sorted?  

Since this is a learning exercise, it won't be the most efficient way of performing the insertion.  It will instead demonstrate the brute-force method in detail.   

Assume you are given the array $arr=[1,2,4,5,3]$ indexed $\boldsymbol{0}...4$.  Store the value of $ar r[4]$.  Now test lower index values successively from $3$ to $\mbox{0}$ until you reach a value that is lower than $ar r[4]$, at $ar r[1]$ in this case.  Each time your test fails, copy the value at the lower index to the current index and print your array.  When the next lower indexed value is smaller than $ar r[4]$, insert the stored value at the current index and print the entire array.

Example 

$n=5$ 

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

Start at the rightmost index.  Store the value of $ar r[4]=3$.  Compare this to each element to the left until a smaller value is reached.  Here are the results as described:  

1 2 4 5 5
1 2 4 4 5
1 2 3 4 5

Function Description

Complete the insertionSort1 function in the editor below.  

insertionSort1 has the following parameter(s):

n: an integer, the size of $\textbf{arr}$  
arr: an array of integers to sort  

Returns  

None:  Print the interim and final arrays, each on a new line.  No return value is expected.  

Input Format

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

The next line contains $n$ space-separated integers $ar r[0]...ar r[n-1]$. 

Constraints

$1\leq n\leq1000$ 

$-10000\leq arr[i]\leq10000$  

Output Format

Print the array as a row of space-separated integers each time there is a shift or insertion.

Sample Input
5
2 4 6 8 3

Sample Output
2 4 6 8 8 
2 4 6 6 8 
2 4 4 6 8 
2 3 4 6 8 

Explanation

$3$ is removed from the end of the array.

In the $1^{st}$ line $8>3$, so $8$ is shifted one cell to the right. 

In the $2^{nd}$ line $6>3$, so $\boldsymbol{6}$ is shifted one cell to the right. 

In the $3^{rd}$ line $4>3$, so $\begin{array}{c}4\end{array}$ is shifted one cell to the right. 

In the $ 4^{th}$ line $2<3$, so $3$ is placed at position $\mbox{1}$.  

Next Challenge

In the next Challenge, we will complete the insertion sort.

Difficulty: EASY

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


s = int(input())
ar = [int(x) for x in input().split()]
x = ar[s - 1]
i = s - 2
while True:
	ar[i + 1] = ar[i]
	i = i - 1
	for n in ar:
		print(n, end=' ')
	print()
	if i == -1 or x >= ar[i]:
		break
ar[i + 1] = x
for x in ar:
	print(x, end=' ')


import sys

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


def insertionSort(m, ar):
	if m == 1:
		print(ar[0])
	else:
		item = ar[-1]
		index = -2
		while index >= -m and item < ar[index]:
			ar[index + 1] = ar[index]
			for element in ar:
				print(element, end=' ')
			print()
			index -= 1
		ar[index + 1] = item
		for element in ar:
			print(element, end=' ')
		print()
m = int(input())
ar = [int(i) for i in input().strip().split()]
insertionSort(m, ar)


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()]
num = array[-1]
for i in range(N - 2, -1, -1):
	if array[i] > num and i != 0:
		array[i + 1] = array[i]
		display(array)
	elif array[i] > num and i == 0:
		array[i + 1] = array[i]
		display(array)
		array[i] = num
		display(array)
	else:
		array[i + 1] = num
		display(array)
		break


x = int(input())
a = input().split()
v = int(a[x - 1])
i = x - 2
found = 0
while i >= 0:
	t = int(a[i])
	if t > v:
		a[i + 1] = t
	else:
		a[i + 1] = v
		found = 1
	for num in a:
		print(num, end=' ')
	print()
	if found:
		break
	i -= 1
if not found:
	a[0] = v
	for num in a:
		print(num, end=' ')
	print()


__author__ = 'Ben'
S = input()
ar = input()
ar = ar.split()
S = ar.__len__() - 1
val = ar[S]
S -= 1
while ar[S] > val and S >= 0:
	ar[S + 1] = ar[S]
	S -= 1
	tmp = ar[S]
	print('%s' % ' '.join(map(str, ar)), '')
ar[S + 1] = val
print('%s' % ' '.join(map(str, ar)), '')


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


def recursive_print(ar):
	if ar == []:
		return ''
	return str(ar[0]) + ' ' + recursive_print(ar[1:])

def insertionSort(ar):
	val = len(ar) - 1
	temp = ar[val]
	while ar[val - 1] > temp and val > 0:
		ar[val] = ar[val - 1]
		val -= 1
		print(recursive_print(ar))
	ar[val] = temp
	print(recursive_print(ar))
input()
ar = input().split()
insertionSort(ar)


import sys

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


size = input()
size = int(size)
text = input()
array = [int(n) for n in text.split()]
oddManOut = array[len(array) - 1]
for a in range(size + 1):
	if not a == 0:
		num = array[size - a - 1]
		if oddManOut < num and (not a == size):
			array[size - a] = num
			printOut = ''
			for c in array:
				printOut = printOut + str(c) + ' '
			print(str(printOut))
		else:
			extraMod = size + 99
			if oddManOut < num:
				extraMod = 1
			array[(size - a) % extraMod] = oddManOut
			printOut = ''
			for c in array:
				printOut = printOut + str(c) + ' '
			print(printOut)
			break


import sys
t = int(input())
a = sys.stdin.readline().split()
idx = t - 1
while True:
	for x in range(0, t):
		if x == idx and idx == 0:
			sys.stdout.write('{} '.format(a[idx]))
		elif x == idx and a[idx - 1] > a[idx]:
			sys.stdout.write('{} '.format(a[idx - 1]))
			(a[idx], a[idx - 1]) = (a[idx - 1], a[idx])
		elif x == idx and a[idx - 1] <= a[idx]:
			sys.stdout.write('{} '.format(a[x]))
			idx = -1
		else:
			sys.stdout.write('{} '.format(a[x]))
	idx = idx - 1
	sys.stdout.write('\n')
	if a[idx + 1] == a[idx] or idx < 0:
		break


import sys
s = int(input())
number = input()
l = [int(s) for s in number.split()]
V = l[s - 1]
next = s - 2
while V < l[next]:
	l[next + 1] = l[next]
	for i in range(0, s):
		print(l[i], end=' ')
	next = next - 1
	print()
	if next < 0:
		break
l[next + 1] = V
for i in range(0, s):
	print(l[i], end=' ')


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

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


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]
key = arr[-1]
j = size - 2
while j >= 0 and arr[j] > key:
	arr[j + 1] = arr[j]
	j -= 1
	printArr(arr)
	print()
arr[j + 1] = key
printArr(arr)


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


def insertionSort(a):
	v = a[-1]
	i = len(a) - 2
	while v <= a[i] and i >= 0:
		a[i + 1] = a[i]
		for ele in a:
			print(ele, end=' ')
		print('')
		i -= 1
	a[i + 1] = v
	for ele in a:
		print(ele, end=' ')
n = int(input())
a = list(map(int, input().split()))
insertionSort(a)


N = int(input())
arr = input().split()
for i in range(N):
	arr[i] = int(arr[i], 10)
v = arr[N - 1]
srt = False
l = N
N = N - 1
while not srt:
	if N == 0 or v > arr[N - 1]:
		arr[N] = v
		srt = True
	else:
		arr[N] = arr[N - 1]
	for j in range(l):
		print(arr[j], end=' ')
	print()
	N = N - 1


s = int(input())
p = s
tmp = input()
ar = tmp.split(' ')
ar = [int(i) for i in ar]
var = ar[s - 1]
flag = False
while not flag:
	if s == 1:
		ar[s - 1] = var
		flag = True
	elif ar[s - 2] > var:
		ar[s - 1] = ar[s - 2]
		s = s - 1
	else:
		ar[s - 1] = var
		flag = True
	ans = ''
	for i in range(p):
		ans = ans + str(ar[i]) + ' '
	print(ans)


def printArray(array):
	for i in range(0, len(array)):
		print(array[i], end=' ')
s = int(input()) - 1
ar = input()
ar = ar.split()
v = int(ar[s])
for x in range(1, s + 1):
	if v < int(ar[s - x]):
		ar[s - x + 1] = ar[s - x]
		printArray(ar)
		print()
		if not s - x:
			ar[0] = v
			printArray(ar)
			break
	else:
		ar[s - x + 1] = v
		printArray(ar)
		break


size = int(input())
array = list(map(int, input().split()))
V = array[size - 1]

def print_array(array):
	for elem in array:
		print(elem, end=' ')
	print('')
for _ in range(size):
	for i in range(size - 1):
		if array[i] > array[i + 1]:
			array[i + 1] = array[i]
			print_array(array)
			array[i] = V
			break
print_array(array)


import fileinput

def insertionSort(ar):
	l = len(ar)
	inserted_element = ar[l - 1]
	index = l - 2
	while inserted_element < ar[index] and index >= 0:
		ar[index + 1] = ar[index]
		print_ar(ar)
		index -= 1
	ar[index + 1] = inserted_element
	print_ar(ar)

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

def get_input():
	count = 1
	for line in fileinput.input():
		if count == 2:
			line = line.rstrip()
			ar = line.split(' ')
		count += 1
	insertionSort(ar)
get_input()


def insertionSort(ar):
	sorted_list = ar
	to_insert = sorted_list[-1]
	i = len(sorted_list) - 2
	comparing = sorted_list[i]
	while to_insert < comparing and i >= 0:
		sorted_list[i + 1] = sorted_list[i]
		i -= 1
		print_list_as_string(sorted_list)
		comparing = sorted_list[i]
	sorted_list[i + 1] = to_insert
	print_list_as_string(sorted_list)

def print_list_as_string(l):
	stri = ''
	for j in l:
		stri += str(j) + ' '
	stri += ''
	print(stri)
m = input()
ar = [int(i) for i in input().strip().split()]
insertionSort(ar)


n = int(input())
ar = [int(num) for num in input().split()]
a = ar[n - 1]
for i in range(n - 2, -1, -1):
	if ar[i] > a:
		ar[i + 1] = ar[i]
		for j in ar:
			print(j, end=' ')
	else:
		ar[i + 1] = a
		for j in ar:
			print(j, end=' ')
		break
	print()
else:
	ar[0] = a
	for j in ar:
		print(j, end=' ')


def pprint(arr):
	row = ''
	for p in arr:
		row = row + str(p) + ' '
	print(row)

def swap(buf, index, arr):
	if buf > arr[index - 1] or index == 0:
		arr[index] = buf
		pprint(arr)
	else:
		arr[index] = arr[index - 1]
		pprint(arr)
		swap(buf, index - 1, arr)
length = int(input())
arr = [int(x) for x in input().split()]
swap(arr[length - 1], length - 1, 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]))
element = data[-1]
try:
	for index in range(1, length):
		if data[-index - 1] <= element:
			raise StopIteration('Place found!')
		data[-index] = data[-index - 1]
		print_list(data)
	data[0] = element
except StopIteration:
	data[-index] = element
print_list(data)


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