Insertion Sort Advanced Analysis – HackerRank Solution

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

Task

Insertion Sort is a simple sorting technique which was covered in previous challenges. Sometimes, arrays may be too large for us to wait around for insertion sort to finish. Is there some other way we can calculate the number of shifts an insertion sort performs when sorting an array?

If k[i] is the number of elements over which the ith element of the array has to shift, then the total number of shifts will be k[1] + k[2] + . . . + k[n].

Example

arr = [4, 3, 2, 1]

Array		Shifts
[4,3,2,1]	
[3,4,2,1]	1
[2,3,4,1]	2
[1,2,3,4]	3

Total shifts = 1 + 2 + 3 = 6

Function description

Complete the insertionSort function in the editor below.

insertionSort has the following parameter(s):

  • int arr[n]: an array of integers

Returns
– int: the number of shifts required to sort the array

Input Format

The first line contains a single integer t, the number of queries to perform.

The following t pairs of lines are as follows:

  • The first line contains an integer n, the length of arr.
  • The second line contains n space-separated integers arr[i].

Constraints

  • 1 <= t <= 15
  • 1 <= n <= 100000
  • 1 <= a[i] <= 10000000

Sample Input

2  
5  
1 1 1 2 2  
5  
2 1 3 1 2

Sample Output

0  
4  

Explanation

The first query is already sorted, so there is no need to shift any elements. In the second case, it will proceed in the following way.

Array: 2 1 3 1 2 -> 1 2 3 1 2 -> 1 1 2 3 2 -> 1 1 2 2 3
Moves:   -        1       -    2         -  1            = 4

Solution – Insertion Sort Advanced Analysis – HackerRank Solution

C++

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

long long iNum = 0;

void cntInv(vector<int>& a, vector<int>& b, int l, int r){
    if(r - l < 2)
        return;
    int mid = (l + r) / 2;
    cntInv(b, a, l, mid);
    cntInv(b, a, mid, r);
    int i = mid - 1;
    int j = r - 1;
    int k = r - 1;
    while(i >= l && j >= mid){
        if(a[j] >= a[i])
            b[k--] = a[j--];
        else{
            iNum += j - mid + 1;
            b[k--] = a[i--];
        }
    }
    while(i >= l){
        b[k--] = a[i--];
    }
    while(j >= mid){
        b[k--] = a[j--];
    }
}

int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */   
    int T;
    cin >> T;
    while(T--){
        vector<int> a;
        int n;
        cin >> n;
        for(int i = 0; i < n; ++i){
            int num;
            cin >> num;
            a.push_back(num);
        }
        vector<int> b(a);
        iNum = 0;
        cntInv(a, b, 0, a.size());

        cout << iNum << endl;
    }
    return 0;
}

Python

from array import array
from bisect import bisect_right

t = int(input())
for _ in range(t):
    n = int(input())
    arr = array('I', [int(i) for i in input().split()])
    sarr = array('I', [arr[0]])
    result = 0
    for i in range(1, n):
        e = arr[i]
        j = bisect_right(sarr, e)       
        sarr.insert(j, e)
        result += i - j
    print(result)  

Java

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {

        Scanner in = new Scanner(System.in);
        int t = in.nextInt();

        for (int i = 0; i < t; i++) {
            int n = in.nextInt();
            int[] ar = new int[n];
            for (int j = 0; j < n; j++) {
                ar[j] = in.nextInt();
                //System.err.println(ar[j]);
            }
            long c = insertSort(ar);
            System.out.println(c);
        }
    }

    static long count = 0;

    public static void mergesort(int[] arr, int p, int r) {
        int q = (p + r) / 2;
        if (p < r) {
            mergesort(arr, p, q);
            mergesort(arr, q + 1, r);
            merge(arr, p, q, r);
        }
    }

    public static void merge(int[] arr, int p, int q, int r) {
        int[] left = new int[q - p + 1];
        int[] right = new int[r - q];
        for (int i = 0; i < left.length; i++) {
            left[i] = arr[p + i];
        }
        for (int i = 0; i < right.length; i++) {
            right[i] = arr[q + i + 1];
        }

        int i = 0, j = 0;
        for (int k = p; k <= r; k++) {
            if (i < left.length && j < right.length) {
                if (left[i] <= right[j]) {
                    arr[k] = left[i];
                    i++;
                } else {
                    arr[k] = right[j];
                    count += left.length - i;
                    j++;
                }
            } else {
                if (i < left.length) {
                    arr[k] = left[i];
                    i++;
                } else if (j < right.length) {
                    arr[k] = right[j];
                    j++;
                }
            }
        }
    }

    public static long insertSort(int[] ar) {
        count = 0;
        mergesort(ar, 0, ar.length - 1);
        return count;

    }
}

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

Leave a Comment

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