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.
Complete the insertionSort2 function below using the insertion sort algorithm to sort an array of integers. As each element is placed in its final position of an iteration, print the array as a string of space-separated integers on its own line.
There will be two lines of input:
- the size of the array
space-separated integers that make up
On each line, output the entire array at every iteration.
Skip testing against itself at position . It is sorted.
Test position against position : , no more to check, no change.
Test position against positions and :
, new position may be . Keep checking.
, so insert at position and move others to the right.
Test position against positions (as necessary): no change.
Test position against positions : no change.
Test position against positions , insert at position and move others to the right.