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 1 Problem Solution

HackerRank Insertion Sort – Part 1 Solution

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

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

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 e in the rightmost cell, can you write some simple code to insert 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 0… 4. Store the value of arr[4] .Now test lower index values successively from 3 to 0 until you reach a value that is lower than arr[4], at arr[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 arr[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 arr[4] = 3. Compare this to each element to the left until a smaller value is reached. Here are the results as described:

12455
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 arr
  • arr. an array of integers to sort

Input Format
The first line contains the integer n, the size of the array arr.
The next line contains n space-separated integers arr[0]… arr[n — 1].

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 1st line 8 > 3, so 8 is shifted one cell to the right.
In the 2nd line 6 > 3, so 6 is shifted one cell to the right.
In the 3rd line 4 > 3, so 4 is shifted one cell to the right.
In the 4th line 2 <3, so 3 is placed at position 1.
Next Challenge
In the next Challenge, we will complete the insertion sort.

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

Table of Contents

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

Insertion Sort – Part 1 C Solution

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

void print_value(int ar_size, int *ar) {
    int i = 0;
    for(;i < ar_size;i++) {
        printf("%d",ar[i]);
        if(i < ar_size - 1) {
            printf(" ");
        }
    }
    printf("\n");
}
/* Head ends here */
void insertionSort(int ar_size, int *  ar) {
    int last_value = ar[ar_size - 1];
    int cur = ar_size - 1;
    while(1) {
        if(cur && ar[cur - 1] > last_value) {
            ar[cur] = ar[cur - 1]; 
            print_value(ar_size, ar);
        }
        else {
            ar[cur] = last_value;
            print_value(ar_size, ar);
            break;
        }
        cur--;
    }


}

/* 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 1 C++ Solution

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>

int n, a[1005];

void print(){for(int i=0;i<n;i++)printf("%d%c",a[i],i==n-1?'\n':' ');}

int main() {
    scanf("%d",&n);
    for(int i=0;i<n;i++) scanf("%d",&a[i]);
    int k=a[n-1],j=n-1;
    for (;j>0 && a[j-1]>k;j--){
        a[j] = a[j-1];
        print();
    }
    a[j]=k;
    print();
    return 0;
}

Insertion Sort – Part 1 C Sharp Solution

using System;
using System.Collections.Generic;
using System.IO;
class Solution
{
    /* Head ends here */
    static void insertionSort(int[] ar)
    {

        int numberToInsert = ar[ar.Length - 1];
        int index = 0;
        string output = "";

        for (int i = ar.Length - 1; i >= 0; i--)
        {
            if (numberToInsert < ar[i])
            {
                ar[i + 1] = ar[i];
                output = "";
                for (int j = 0; j < ar.Length; j++)
                {
                    output = output + ar[j].ToString() + " ";
                }
                Console.WriteLine(output);
                index = i;
            }
        }


        ar[index] = numberToInsert;
        output = "";
        for (int j = 0; j < ar.Length; j++)
        {
            output = output + ar[j].ToString() + " ";
        }
        Console.WriteLine(output);
        
    }
    /* Tail starts here */
    /* Tail starts 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);
    }
}

Insertion Sort – Part 1 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 'insertionSort1' function below.
     *
     * The function accepts following parameters:
     *  1. INTEGER n
     *  2. INTEGER_ARRAY arr
     */

    public static void insertionSort1(int n, List<Integer> arr) {
    // Write your code here
        for (int i = 1; i < arr.size(); i++){
            int j;
            int v = arr.get(i);
            for (j = i-1; j>=0; j--){
                if (arr.get(j) <= v){
                    break;
                }
                arr.set(j+1, arr.get(j));
                arr.forEach(x -> System.out.print(x + " "));
                System.out.println();
            }
            arr.set(j+1, v);
            
        }
        arr.forEach(x -> System.out.print(x + " "));

    }

}

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.insertionSort1(n, arr);

        bufferedReader.close();
    }
}

Insertion Sort – Part 1 JavaScript Solution

function processData(input)
{
    //Enter your code here
    var array_size = parseInt(input.split('\n')[0], 10);
    var numbers = input.split('\n')[1].split(' ');
    var idx = array_size - 1;
    var number = numbers[idx];
    for( ; numbers[idx-1]>number && array_size>0 ; --idx, --array_size)
    {
        numbers[idx] = numbers[idx-1];
        printData(numbers);
    }
    
    numbers[idx] = number;
    printData(numbers);
} 

function printData(data)
{
    for( var i=0 ; i < data.length ; ++i )
    {
        process.stdout.write(data[i] + ' ');
    }
    process.stdout.write('\n');
}

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 1 Python Solution

def main():
    s = int(input())
    unsorted = list(map(int, input().rstrip().split()))
    item = unsorted[-1]
    marker = len(unsorted) - 2
    while item < unsorted[marker] and marker >= 0:
        unsorted[marker+1] = unsorted[marker]
        strUnsorted = list(map(str, unsorted))
        print(" ".join(strUnsorted))
        marker-=1
    unsorted[marker+1] = item
    strUnsorted = list(map(str, unsorted))
    print(" ".join(strUnsorted))
    return 0

main()

Other Solutions

  • HackerRank Strong Password Problem Solution
  • HackerRank Two Characters Problem Solution
c, C#, C++, HackerRank Solutions, java, javascript, python Tags:C, cpp, CSharp, Hackerrank Solutions, java, javascript, python

Post navigation

Previous Post: HackerRank CamelCase Problem Solution
Next Post: HackerRank Strong Password Problem Solution

Related Posts

HackerRank Intro to Tutorial Challenges Problem Solution HackerRank Intro to Tutorial Challenges Solution c
HackerRank Sequence Equation Problem Solution HackerRank Sequence Equation Problem Solution c
HackerRank Drawing Book Problem Solution HackerRank Drawing Book Problem Solution c
HackerRank Simple Array Sum Problem Solution HackerRank Simple Array Sum Problem Solution c
HackerRank Kingdom Connectivity Problem Solution HackerRank Kingdom Connectivity Solution c
HackerRank Strong Password Problem Solution HackerRank Strong Password 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