Running Time of Algorithms HackerRank Solution in C, C++, Java, Python

In a previous challenge you implemented the Insertion Sort algorithm. It is a simple sorting algorithm that works well with small or mostly sorted data. However, it takes a long time to sort large unsorted data. To see why, we will analyze its running time.

Running Time of Algorithms

The running time of an algorithm for a specific input depends on the number of operations executed. The greater the number of operations, the longer the running time of an algorithm. We usually want to know how many operations an algorithm will execute in proportion to the size of its input, which we will call N.

What is the ratio of the running time of Insertion Sort to the size of the input? To answer this question, we need to examine the algorithm.

Analysis of Insertion Sort

For each element V in an array of N numbers, Insertion Sort compares the number to those to its left until it reaches a lower value element or the start. At that point it shifts everything to the right up one and inserts V into the array.

How long does all that shifting take?

In the best case, where the array was already sorted, no element will need to be moved, so the algorithm will just run through the array once and return the sorted array. The running time would be directly proportional to the size of the input, so we can say it will take N time.

However, we usually focus on the worst-case running time (computer scientists are pretty pessimistic). The worst case for Insertion Sort occurs when the array is in reverse order. To insert each number, the algorithm will have to shift over that number to the beginning of the array. Sorting the entire array of N numbers will therefore take 1+2+…+(N-1) operations, which is  N(N-1)/2 (almost N^2/2). Computer scientists just round that up (pick the dominant term) to  and say that Insertion Sort is an “N^2 time” algorithm.

What this means

The running time of the algorithm against an array of N elements is N^2. For 2N elements, it will be 4N^2. Insertion Sort can work well for small inputs or if you know the data is likely to be nearly sorted, like check numbers as they are received by a bank. The running time becomes unreasonable for larger inputs.


Can you modify your previous Insertion Sort implementation to keep track of the number of shifts it makes while sorting? The only thing you should print is the number of shifts made by the algorithm to completely sort the array. A shift occurs when an element’s position changes in the array. Do not shift an element if it is not necessary.

Function Description

Complete the runningTime function in the editor below. It should return an integer representing the number of shifts it will take to sort the given array.

runningTime has the following parameter(s):

  • arr: an array of integers

Input Format

The first line contains the integer , the number of elements to be sorted.

The next line contains  integers of .



10000<=a[i]<=100000, wher i = {0..(n-1)}

Output Format

Output the number of shifts it takes to sort the array.

Sample Input


2 1 3 1 2


Sample Output




Iteration   Array      Shifts

0           2 1 3 1 2

1           1 2 3 1 2     1

2           1 2 3 1 2     0

3           1 1 2 3 2     2

4           1 1 2 2 3     1

Total                     4


Running Time of Algorithms 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 *shifts) {
int temp=ar[ar_size-1],i;
        if(ar[i]>temp){ ar[i+1]=ar[i];*shifts=*shifts+1;}
        else break;


/* Tail starts here */
int main() {
   int _ar_size,i,j,shifts=0;
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(i, _ar,&shifts);    
   return 0;


Running Time of Algorithms HackerRank Solution in C++

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

int insertionSortCount(vector <int>  ar) {
    int n = ar.size();
    int count=0;
    for(int i=1;i<n;i++){
        int curr = ar[i];
        for(int j=i-1;j>=0;j--){
    return count;

/* 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;
    return 0;


Running Time of Algorithms HackerRank Solution in Java

/* Head ends here */
import java.util.*;
public class Solution {
static void insertionSort(int[] ar) {
              int count =0;              
              for(int i=1;i<ar.length;i++){	                  
            	  int n= ar[i];
            	  int j=i-1;
            	  while(j>=0 && ar[j]>n){	
            		  //System.err.print(i+" ");
            		  ar[j+1]=ar[j]; //shift right			
        ar[j+1]= n;           
              System.out.println( count);

/* Tail starts here */
      public static void main(String[] args) {
           Scanner in = new Scanner(;
           int n = in.nextInt();
           int[] ar = new int[n];
           for(int i=0;i<n;i++){


Running Time of Algorithms HackerRank Solution in Python

n = int(raw_input())
ar = [int(c) for c in raw_input().split()]

cnt = 0
for i in range(1, n):
    v = ar[i]
    k = i - 1
    while k >=0 and ar[k] > v:
        ar[k + 1] = ar[k]
        k -= 1
        cnt += 1
    ar[k + 1] = v
print cnt


Running Time of Algorithms HackerRank Solution in C#

using System;
using System.Collections.Generic;
using System.IO;
class Solution
    static void Main(String[] args)
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution */
        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]);

    public static int InsertionSort(int[] array)
        int n = array.Length;
        int count = 0;
        for (int i = 1; i < n; i++)
            for (int j = i - 1; j >= 0 && array[j] > array[j + 1]; j--)
                swap(ref array[j], ref array[j + 1]);

        return count;

    private static void swap(ref int a, ref int b)
        int temp = a;
        a = b;
        b = temp;


Attempt Running Time of Algorithms HackerRank Challenge

Link –

Next HackerRank Challenge Solution 

Link –

Leave a Comment