Skip to content
  • Home
  • Contact Us
  • About Us
  • Privacy Policy
  • DMCA
  • Linkedin
  • Pinterest
  • Facebook
thecscience

TheCScience

TheCScience is a blog that publishes daily tutorials and guides on engineering subjects and everything that related to computer science and technology

  • Home
  • Human values
  • Microprocessor
  • Digital communication
  • Linux
  • outsystems guide
  • Toggle search form
HackerRank Insertion Sort - Part 2 Problem Solution

HackerRank Insertion Sort – Part 2 Solution

Posted on April 23, 2023April 28, 2023 By Yashwant Parihar No Comments on HackerRank Insertion Sort – Part 2 Solution

In this post, we will solve HackerRank Insertion Sort – Part 2 Problem Solution.

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].

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 > 1, so insert 3 at position 1 and move others to the right.
  • 3 < 4, new position may be 1. Keep checking.


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

HackerRank Insertion Sort - Part 2 Problem Solution
HackerRank Insertion Sort – Part 2 Problem Solution

Table of Contents

  • Insertion Sort – Part 2 C Solution
  • Insertion Sort – Part 2 C++ Solution
  • Insertion Sort – Part 2 C Sharp Solution
  • Insertion Sort – Part 2 Java Solution
  • Insertion Sort – Part 2 JavaScript Solution
  • Insertion Sort – Part 2 Python Solution

Insertion Sort – Part 2 C Solution

#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;
}

Insertion Sort – Part 2 C++ Solution

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

void insertionSort(vector<int> &ar) {
    for(int i = 1; i < ar.size(); ++i) {
        int temp = ar[i];
        for(int j = i; j >=0; j--) {
            if(ar[j-1] > temp) { ar[j] = ar[j-1]; }
            else { ar[j] = temp; break; }
        }
        for(auto &x : ar) cout << x << " "; cout << endl;
    }
}

int main() {
    int N; cin >> N;
    vector<int> A(N); for(int i = 0; i < N; i++) cin >> A[i];
    insertionSort(A);
    return 0;
}

Insertion Sort – Part 2 C Sharp Solution

using System;
using System.Collections.Generic;
using System.IO;
class Solution {
/* Head ends here */
           static void Main(String[] args)
        {

            int _ar_size;
            _ar_size = Convert.ToInt32(Console.ReadLine());
            int[] _ar = new int[_ar_size];
            String elements = Console.ReadLine();
            String[] split_elements = elements.Split(' ');
            for (int _ar_i = 0; _ar_i < _ar_size; _ar_i++)
            {
                _ar[_ar_i] = Convert.ToInt32(split_elements[_ar_i]);
            }

            insertionSort(_ar);
        }
        static void insertionSort(int[] ar)
        {
         int tmp=0,j,i;
            int k, counter = 1;
            bool specialCase = false;


           
            if(ar.Length == 1) {specialCase = true; goto print;}

                for (k = 0; k < ar.Length - 1; k++)
                {
                    if(counter < ar.Length) tmp = ar[counter];
                    i = k;
                    while (i >= 0 && tmp < ar[i])
                    {
                        j = ar[i];
                        ar[i] = tmp;
                        ar[i + 1] = j;
                        i--;

                    }
                    for (int x = 0; x < ar.Length; x++)
                        Console.Write("{0} ", ar[x]);
                    Console.WriteLine();
                    counter++;
                }
             print:   if (specialCase)
                {
                    ar[0] = tmp;
                 for (int x = 0; x < ar.Length; x++)
                        Console.Write("{0} ", ar[x]);
                    Console.WriteLine();

                }
             
           

        }
}

Insertion Sort – Part 2 Java Solution

import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;

class Result {

    /*
     * Complete the 'insertionSort2' function below.
     *
     * The function accepts following parameters:
     *  1. INTEGER n
     *  2. INTEGER_ARRAY arr
     */

    public static void insertionSort2(int n, List<Integer> arr) {
        for (int i=1; i<n; i++){
            insertionSort1(i, arr);
            print(arr);
        }

    }
    
    
    
    
      public static void print(List<Integer> arr){
        System.out.println(arr.stream().map(String::valueOf).collect(Collectors.joining(" ")));
    }

     public static void insertionSort1(int n, List<Integer> arr) {
        // Write your code here
        int val = arr.get(n);
        int i = n-1;
        while (i >= 0){
            int comp = arr.get(i);
            if (comp > val){
                arr.set(i+1, comp);
            }
            else {
                arr.set(i+1, val);
                return;
            }

            i--;
        }
        arr.set(0, val);
    }

}

public class Solution {
    public static void main(String[] args) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));

        int n = Integer.parseInt(bufferedReader.readLine().trim());

        List<Integer> arr = Stream.of(bufferedReader.readLine().replaceAll("\\s+$", "").split(" "))
            .map(Integer::parseInt)
            .collect(toList());

        Result.insertionSort2(n, arr);

        bufferedReader.close();
    }
}

Insertion Sort – Part 2 JavaScript Solution

function processData(input) {
    var lines = input.split("\n");
    
    var N = parseInt(lines.shift());
    var list = lines.shift().split(" ");

    var i, last, before;
    for (i=1; i<list.length; i++){
        var j = i;
        do {
            last = list[j] = parseInt(list[j]);
            before = list[j-1] = parseInt(list[j-1]);
            if (last < before){
                swap(list, j, j-1);
            }
            j--;
        } while (j>0 && last < before)
        
        print(list);
    }
}
    
function print(A){
    var str = "";
    for (var i=0; i<A.length; i++){
        str += A[i] + " ";
    }
    console.log(str);
}

function swap(A, i1, i2){
    var aux = A[i1];
    A[i1] = A[i2];
    A[i2] = aux;
}

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

process.stdin.on("end", function () {
   processData(_input);
});

Insertion Sort – Part 2 Python Solution

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

Other Solutions

  • HackerRank Correctness and the Loop Invariant
  • HackerRank Caesar Cipher Problem Solution
c, C#, C++, HackerRank Solutions, java, javascript, python Tags:C, cpp, CSharp, Hackerrank Solutions, java, javascript, python

Post navigation

Previous Post: HackerRank Two Characters Problem Solution
Next Post: HackerRank Correctness and the Loop Invariant

Related Posts

HackerRank Sherlock and The Beast Problem Solution HackerRank Sherlock and The Beast Solution c
HackerRank Problem solving Problem Solution HackerRank Problem solving Problem Solution c
HackerRank Jogging Cats Problem Solution HackerRank Jogging Cats Problem Solution c
HackerRank Candies Problem Solution HackerRank Candies Problem Solution c
HackerRank Manasa and Stones Problem Solution HackerRank Manasa and Stones Problem Solution c
HackerRank Bead Ornaments Problem Solution HackerRank Bead Ornaments Problem Solution c

Leave a Reply Cancel reply

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

Pick Your Subject
Human Values

Copyright © 2023 TheCScience.

Powered by PressBook Grid Blogs theme