Insertion Sort Advanced Analysis


Problem Statement :


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?


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  <=  arr[i]  <=   10000000



Solution :



title-img


                            Solution in C :

In   C++  :








#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std ;
#define MAXN 100002
#define MAX 1000002
int n,a[MAXN],c[MAX] ;
int main()
{
 int runs ;
 scanf("%d",&runs) ;
 while(runs--)
 {
  scanf("%d",&n) ;
  for(int i = 0;i < n;i++) scanf("%d",&a[i]) ;
  long long ret = 1LL * n * (n - 1) / 2 ;
  memset(c,0,sizeof c) ;
  for(int i = 0;i < n;i++)
  {
   for(int j = a[i];j > 0;j -= j & -j) ret -= c[j] ;
   for(int j = a[i];j < MAX;j += j & -j) c[j]++ ;  
  }
  cout << ret << endl ;
 }
 return 0 ;
}










In   Java  :








import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;



public class Solution 
{

    public static void main(String[] args) throws Exception 
    {
 BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int T,N,t,j;
        int[] nums;
        T = Integer.parseInt(br.readLine());
        for (t = 0; t < T; t++) 
        {
            N = Integer.parseInt(br.readLine());
            nums = new int[N];
            String[] strs = br.readLine().split(" ");
            for (j = 0; j < N; j++)
                nums[j] = Integer.parseInt(strs[j]);
            System.out.print(Long.toString(sort_and_count(nums, 0, N - 1))+"\n");
            
        }
        
    }

    public static long sort_and_count(int[] a, int x1, int x2) 
    {
        if (x2 <= x1)
            return 0L;
        if (x2 == x1 + 1)
        {
            if (a[x1] > a[x2]) 
            {
                a[x1] ^= a[x2];
                a[x2] ^= a[x1];
                a[x1] ^= a[x2];
                return 1L;
            }
            return 0L;
        }
        int mid = (x2 + x1) / 2;
        long count = 0L;
        count += sort_and_count(a, x1, mid);
        count += sort_and_count(a, mid + 1, x2);
        count += merge_and_count(a, x1, mid, mid + 1, x2);
        return count;
    }

    public static long merge_and_count(int[] a, int x1, int x2, int y1, int y2) 
    {
        long count = 0L;
        for (int i = x1, j = y1; i <= x2 && j <= y2;) 
        {
            if (a[i] > a[j]) 
            {
                count += (long) (x2 - i + 1);
                j++;
            }
            else
                i++;
        }
        Arrays.sort(a, x1, y2 + 1);
        return count;
    }

    public static long insertSort(int[] a) 
    {
        long count = 0;
        int i,j;
        for (i = 1; i < a.length; i++) 
        {
            j = i;
            while (j >= 1 && a[j] < a[j - 1]) 
            {
                a[j] ^= a[j - 1];
                a[j - 1] ^= a[j];
                a[j] ^= a[j - 1];
                count++;
                j--;
            }
        }
        return count;
    }
}










In  C  :







#include<stdio.h>
unsigned long long int cnt;
int main()
{
        int *p,t,i,n;
        scanf("%d",&t);
        while(t--)
        {
                cnt=0;
                scanf("%d",&n);
                p=(int*)malloc(sizeof(int)*n);
                for(i=0;i<n;i++)
                        scanf("%d",&p[i]);
                merge(p,0,n-1);
                printf("%llu\n",cnt);
        }
        return 0;
}
int merge(int *p,int l,int h)
{
        int m;
        if(l<h)
        {
                m=(l+h)/2;
                merge(p,l,m);
                merge(p,m+1,h);
                sort(p,l,m,h);
        }
}
int sort(int *p,int l,int m,int h)
{
        int i=l,j=m+1,n=0,*k;
        k=(int *)malloc(sizeof(int)*(h-l+1));
        while(i<=m&&j<=h)
        {
                if(p[i]<=p[j])
                        k[n++]=p[i++];
                else
                {
                        cnt+=(m-i+1);
                        k[n++]=p[j++];
                }
        }
        while(i<=m)
                k[n++]=p[i++];
        while(j<=h)
                k[n++]=p[j++];
        for(i=0;i<(h-l+1);i++)
                p[l+i]=k[i];
}
 









In  Python3 :







def mergeSort(m):
    if len(m) <= 1:
        return [0, m]
    mid = len(m)//2
    l = []
    r = []
    for i in range(mid):
        l.append(m[i])
    for i in range(mid, len(m)):
        r.append(m[i])
    left = mergeSort(l)
    right = mergeSort(r)
    return merge(left, right)

def merge(left, right):
    i = 0
    j = 0
    result = []
    num = left[0] + right[0]
    while i < len(left[1]) or j < len(right[1]):
        if i < len(left[1]) and j < len(right[1]):
            if left[1][i] <= right[1][j]:
                result.append(left[1][i])
                i += 1
                num += j
            else:
                result.append(right[1][j])
                j += 1
        elif i < len(left[1]):
            result.append(left[1][i])
            i += 1
            num += j
        elif j < len(right[1]):
            result.append(right[1][j])
            j += 1
    return [num, result]

T = int(input())
for i in range(T):
    n = int(input())
    nums = [int(i) for i in input().split()]
    print(mergeSort(nums)[0])
                        








View More Similar Problems

Tree: Height of a Binary Tree

The height of a binary tree is the number of edges between the tree's root and its furthest leaf. For example, the following binary tree is of height : image Function Description Complete the getHeight or height function in the editor. It must return the height of a binary tree as an integer. getHeight or height has the following parameter(s): root: a reference to the root of a binary

View Solution →

Tree : Top View

Given a pointer to the root of a binary tree, print the top view of the binary tree. The tree as seen from the top the nodes, is called the top view of the tree. For example : 1 \ 2 \ 5 / \ 3 6 \ 4 Top View : 1 -> 2 -> 5 -> 6 Complete the function topView and print the resulting values on a single line separated by space.

View Solution →

Tree: Level Order Traversal

Given a pointer to the root of a binary tree, you need to print the level order traversal of this tree. In level-order traversal, nodes are visited level by level from left to right. Complete the function levelOrder and print the values in a single line separated by a space. For example: 1 \ 2 \ 5 / \ 3 6 \ 4 F

View Solution →

Binary Search Tree : Insertion

You are given a pointer to the root of a binary search tree and values to be inserted into the tree. Insert the values into their appropriate position in the binary search tree and return the root of the updated binary tree. You just have to complete the function. Input Format You are given a function, Node * insert (Node * root ,int data) { } Constraints No. of nodes in the tree <

View Solution →

Tree: Huffman Decoding

Huffman coding assigns variable length codewords to fixed length input characters based on their frequencies. More frequent characters are assigned shorter codewords and less frequent characters are assigned longer codewords. All edges along the path to a character contain a code digit. If they are on the left side of the tree, they will be a 0 (zero). If on the right, they'll be a 1 (one). Only t

View Solution →

Binary Search Tree : Lowest Common Ancestor

You are given pointer to the root of the binary search tree and two values v1 and v2. You need to return the lowest common ancestor (LCA) of v1 and v2 in the binary search tree. In the diagram above, the lowest common ancestor of the nodes 4 and 6 is the node 3. Node 3 is the lowest node which has nodes and as descendants. Function Description Complete the function lca in the editor b

View Solution →