Insertion Sort – Part 1 HackerRank Solution in C, C++, Java, Python

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,3,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:

1 2 4 5 5

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

Returns

  • None: Print the interim and final arrays, each on a new line. No return value is expected.

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

Constraints

1<=n<=1000

1000<=arr[i]<=10000

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.

 

Insertion Sort – Part 1 HackerRank Solution in C

#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) {
    int v;
    int idx;
    int i;
    int done = 0;
    
    v = ar[ar_size - 1];

    for (idx = ar_size-2; idx >= 0; idx--) {
        if (v > ar[idx]) {
            ar[idx+1] = v;
            done = 1;
        } else {
            ar[idx+1] = ar[idx];
        }
        for (i = 0; i < ar_size; i++)
            printf("%d ", ar[i]);
        printf("\n");
        
        if (done)
            break;
    }
    
    if (!done) {
        ar[0] = v;
            for (i = 0; i < ar_size; i++)
            printf("%d ", ar[i]);
        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 1 HackerRank Solution in C++

#include <map>
#include <set>
#include <list>
#include <cmath>
#include <ctime>
#include <deque>
#include <queue>
#include <stack>
#include <bitset>
#include <cstdio>
#include <vector>
#include <cstdlib>
#include <numeric>
#include <sstream>
#include <iostream>
#include <algorithm>
using namespace std;

/* Head ends here */

void insertionSort(vector <int>  ar) {
    int n = ar.size();
    if(n==0)
        return;
    if(n==1)
        cout<<ar[n-1]<<endl;
    int curr = ar[n-1];
    int i=n-2;
    while(i>=0){
        if(ar[i]>=curr){
            ar[i+1]=ar[i];
        }
        else{
            ar[i+1]=curr;
            i=-1;
        }
        for(int j=0;j<n;j++)
            cout<<ar[j];
        cout<<endl;
        if(i==0){
            ar[i]=curr;
            for(int j=0;j<n;j++)
                cout<<ar[j];
            cout<<endl;
        }
        i--;
    }

}


/* Tail starts here */
int main() {
   vector <int>  _ar;
   int _ar_size;
cin >> _ar_size;
for(int _ar_i=0; _ar_i<_ar_size; _ar_i++) {
   int _ar_tmp;
   cin >> _ar_tmp;
   _ar.push_back(_ar_tmp); 
}

insertionSort(_ar);
   
   return 0;
}

 

Insertion Sort – Part 1 HackerRank Solution in Python

n = int(raw_input())
test = raw_input()
a = test.split()
val = a[n-1]
for i in range(n-2,-2,-1):
    test=test.split()
    if i == -1:
        test[i+1] = val
        break
    elif int(test[i])>int(val):
        test[i+1]=test[i]
    
    else:
        test[i+1] = val
        break
    test = ' '.join(test)
    print test  
test = ' '.join(test)
print test

 

Insertion Sort – Part 1 HackerRank Solution in Java

import java.util.Scanner;

public class Solution {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
       Scanner scan=new Scanner(System.in);
        int s=scan.nextInt();
        int ar[]=new int[s];
        boolean check=false;
        for(int i=0;i<s;i++)
        {
            ar[i]=scan.nextInt();
        }
        int var=ar[s-1];
        for(int i=s-2;i>=-1;i--)
        {
            if(i!=-1)
            {
            if(var<ar[i])
            {
                ar[i+1]=ar[i];
            }
            else
            {
                ar[i+1]=var;
                check=true;
            }
            }
            else
            {
                ar[0]=var;
            }
            for(int j=0;j<s;j++)
                System.out.print(ar[j]+" ");
            System.out.println();
            if(check)
                break;
        }
    }
}

 

Insertion Sort – Part 1 HackerRank Solution in C#

using System;
using System.Collections.Generic;
using System.IO;
class Solution
{

    /* Head ends here */

    static void insertionSort(int[] ar)
    {
        if (ar == null)
            return;
        int length = ar.Length;
        int p = ar[length - 1];
        if (length == 1)
            PrintArray(ar);
        for (int i = length - 2; i >= 0; i--)
        {
            if (ar[i] > p)
            {
                ar[i + 1] = ar[i];
                if (i == 0)
                {
                    PrintArray(ar);
                    ar[i] = p;
                }
                PrintArray(ar);
            }
            else
            {
                ar[i + 1] = p;
                PrintArray(ar);
                return;
            }

        }
    }

    static void PrintArray(int[] ar)
    {
        int length = ar.Length;
        for (int i = 0; i < length; i++)
        {
            if (i == length - 1)
                Console.Write(ar[i]);
            else
                Console.Write(ar[i] + " ");
        }
        Console.WriteLine();
    }


    /* Tail starts here */
    static void Main(String[] args)
    {

        int _ar_size;
        _ar_size = Convert.ToInt32(Console.ReadLine());
        int[] _ar = new int[_ar_size];
        string input = Console.ReadLine();
        string[] inputs = input.Split(' ');

        for (int _ar_i = 0; _ar_i < _ar_size; _ar_i++)
        {
            _ar[_ar_i] = Convert.ToInt32(inputs[_ar_i]);
        }
        insertionSort(_ar);
        Console.ReadKey();
    }
}

 

Attempt Insertion Sort – Part 1 HackerRank Challenge

Link – https://www.hackerrank.com/challenges/insertionsort1/

Next HackerRank Challenge Solution 

Link – https://exploringbits.com/strong-password-hackerrank-solution/

Leave a Comment