Skip to content
Programmingoneonone
Programmingoneonone
  • Engineering Subjects
    • Internet of Things (IoT)
    • Digital Communication
    • Human Values
  • Programming Tutorials
    • C Programming
    • Data structures and Algorithms
    • 100+ Java Programs
    • 100+ C Programs
    • 100+ C++ Programs
  • Solutions
    • HackerRank
      • Algorithms Solutions
      • C solutions
      • C++ solutions
      • Java solutions
      • Python solutions
    • Leetcode Solutions
    • HackerEarth Solutions
  • Work with US
Programmingoneonone
Programmingoneonone

Hackerrank Insertion Sort – Part 2 problem solution

YASH PAL, 31 July 202423 January 2026

Hackerrank Insertion Sort – Part 2 problem solution – In this Hackerrank Insertion Sort – Part 2 problem we have given a sorted list and we need to print the list or array after each insertion of the insertion sort.

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.

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.

Hackerrank Insertion Sort  - Part 2 problem solution

Hackerrank Insertion Sort – Part 2 problem solution in Python.

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()

Insertion Sort – Part 2 problem solution in Java.

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

public class Solution {

    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();
        }
        insertionSort(ar);
    }
        
    public static void insertionSort(int[] ar){
        int a; int b;
        for(a = 0, b = a + 1; b < ar.length; a++, b++){
            int temp = ar[b];
            int i = a;
            while(i >= 0 && temp < ar[i]){
                ar[i + 1] = ar[i];
                i--;
            }
            ar[i + 1] = temp;
            for(int j = 0; j < ar.length; j++){
                System.out.print(ar[j] + " ");
            }
            System.out.print("n");
        }
        
    }   
    
}

Problem solution in C++ programming.

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

#define N 1010

int s;
int ar[N];
void print() {
    for (int i = 0; i < s - 1; i ++) cout << ar[i] << ' ';
    cout << ar[s - 1] << endl; 
}
int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */   
    cin >> s;
    for (int i = 0; i < s; i ++) cin >> ar[i];
    for (int i = 1; i < s; i ++) {
        int val = ar[i], pre = i - 1;
        while (pre >= 0 && ar[pre] > val) {
            ar[pre + 1] = ar[pre];
            pre --;
        }
        ar[pre + 1] = val;
        print();
    }
    return 0;
}

Problem solution in C programming.

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <assert.h>

/* Head ends here */
void insertionSort(int ar_size, int *  ar) {
    for (int i = 1; i < ar_size; ++i) {
        int j = i - 1;
        int p = ar[i];
        while (j >= 0 && p < ar[j]) {
            ar[j+1] = ar[j];
            j--;
        }
        ar[j+1] = p;
        printf("%d", ar[0]);
        for (int k = 1; k < ar_size; ++k) {
            printf(" %d", ar[k]);
        }
        printf("n");
    }
}

/* Tail starts here */
int main() {
   
   int _ar_size;
scanf("%d", &_ar_size);
int _ar[_ar_size], _ar_i;
for(_ar_i = 0; _ar_i < _ar_size; _ar_i++) { 
   scanf("%d", &_ar[_ar_i]); 
}

insertionSort(_ar_size, _ar);
   
   return 0;
}

Problem solution in JavaScript programming.

function processData(input) {
    for(var j = 1; j < input.length; j++) {
        var unsorted = input[j];
        
        for(var i = j-1; i > -1; i--) {
            if(unsorted < input[i]) {
                input[i+1] = input[i];
                input[i] = unsorted;
            } else {
                input[i+1] = unsorted;
                break;
            }
        }

        console.log(input.join(' '));
    }
} 

process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
    _input += input;
});

process.stdin.on("end", function () {
   _input = _input.split("n");
   _input = _input[1].split(" ").map(function(i) { return parseInt(i) });
   processData(_input);
});

Algorithms coding problems solutions AlgorithmsHackerRank

Post navigation

Previous post
Next post

Leave a Reply

Your email address will not be published. Required fields are marked *

Programmingoneonone

We at Programmingoneonone, also known as Programming101 is a learning hub of programming and other related stuff. We provide free learning tutorials/articles related to programming and other technical stuff to people who are eager to learn about it.

Pages

  • About US
  • Contact US
  • Privacy Policy

Practice

  • Java
  • C++
  • C

Follow US

  • YouTube
  • LinkedIn
  • Facebook
  • Pinterest
  • Instagram
©2026 Programmingoneonone | WordPress Theme by SuperbThemes