# Insertion Sort – Part 2 – HackerRank Solution

In this post, we will solve Insertion Sort – Part 2 HackerRank Solution. This problem (Insertion Sort – Part 2) is a part of HackerRank Problem Solving series.

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Â 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Â arr.
The next line containsÂ nÂ space-separated integersÂ arr[i].

## Constraints

• 1 <= n <= 1000
• -10000 <= arr[i] <= 10000, 0 <= i < 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Â 1Â against itself at positionÂ 0. It is sorted.
Test positionÂ 1Â against positionÂ 0:Â 4 > 1, no more to check, no change.
PrintÂ arr
Test positionÂ 2Â against positionsÂ 1Â andÂ 0:

• 3 < 4, new position may beÂ 1. Keep checking.
• 3 > 1, so insertÂ 3Â at positionÂ 1Â and move others to the right.

PrintÂ arr
Test positionÂ 3Â against positionsÂ 2, 1, 0Â (as necessary): no change.
PrintÂ arr
Test positionÂ 4Â against positionsÂ 3, 2, 1, 0: no change.
PrintÂ arr
Test positionÂ 5Â against positionsÂ 4, 3, 2, 1, 0, insertÂ 2Â at positionÂ 1Â and move others to the right.
PrintÂ arr

## Solution – Insertion Sort – 2 – HackerRank Solution

### C++

```#include <cstdio>
#include <cstring>
#include <string>
#include <cmath>
#include <cstdlib>
#include <cassert>
#include <iostream>
using namespace std;

void insertionSort(int ar_size, int *  ar) {
for(int i = 1; i < ar_size; i++) {
int V = ar[i];
for(int j = i; j >= 0; j--) {
if(V < ar[j-1]) {
ar[j] = ar[j-1];
} else {
ar[j] = V;
break;
}
}
// Print the array after each iteration
for(int i = 0; i < ar_size; i++) {
cout<<ar[i]<<" ";
}
cout<<"\n";
}
}

int main(void) {

int _ar_size;
cin >> _ar_size;

int _ar[_ar_size], _ar_i;
for(_ar_i = 0; _ar_i < _ar_size; _ar_i++) {
cin >> _ar[_ar_i];
}

insertionSort(_ar_size, _ar);

return 0;
}
```

### Python

```import sys

def insertionSort1(start, arr):
probe = arr[start]

for ind in range(start-1, -1, -1):
if arr[ind] > probe:
arr[ind+1] = arr[ind]
else:
arr[ind+1] = probe
break
if arr[0] > probe:
arr[0] = probe

def insertionSort2(n, arr):
for ind in range(1, len(arr)):
insertionSort1(ind, arr)
print(" ".join(map(str, arr)))

if __name__ == "__main__":
n = int(input().strip())
arr = list(map(int, input().strip().split(' ')))
insertionSort2(n, arr)
```

### Java

```import java.io.*;
import java.util.*;

public class Solution {

public static void insertionSortPart2(int[] ar, int s)
{
// Fill up the code for the required logic here
// Manipulate the array as required
// The code for Input/Output is already provided
for(int i=0;i<s-1;i++){
int j = i+1;
while(j>0){
if(ar[j]<ar[j-1]){
int temp = ar[j];
ar[j] = ar[j-1];
ar[j-1] = temp;
j--;
}else{
break;
}
}
printArray(ar);
}
}

public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int s = in.nextInt();
int[] ar = new int[s];
for(int i=0;i<s;i++){
ar[i]=in.nextInt();
}
insertionSortPart2(ar,s);
//printArray(ar);

}
private static void printArray(int[] ar) {
for(int n: ar){
System.out.print(n+" ");
}
System.out.println("");
}
}
```

Note: This problem (Insertion Sort – 2) is generated by HackerRank but the solution is provided by CodingBroz. This tutorial is only for Educational and Learning purpose.