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

Minimum Average Waiting Time

Tieu owns a pizza restaurant and he manages it in his own way. While in a normal restaurant, a customer is served by following the first-come, first-served rule, Tieu simply minimizes the average waiting time of his customers. So he gets to decide who is served first, regardless of how sooner or later a person comes. Different kinds of pizzas take different amounts of time to cook. Also, once h

View Solution →

Merging Communities

People connect with each other in a social network. A connection between Person I and Person J is represented as . When two persons belonging to different communities connect, the net effect is the merger of both communities which I and J belongs to. At the beginning, there are N people representing N communities. Suppose person 1 and 2 connected and later 2 and 3 connected, then ,1 , 2 and 3 w

View Solution →

Components in a graph

There are 2 * N nodes in an undirected graph, and a number of edges connecting some nodes. In each edge, the first value will be between 1 and N, inclusive. The second node will be between N + 1 and , 2 * N inclusive. Given a list of edges, determine the size of the smallest and largest connected components that have or more nodes. A node can have any number of connections. The highest node valu

View Solution →

Kundu and Tree

Kundu is true tree lover. Tree is a connected graph having N vertices and N-1 edges. Today when he got a tree, he colored each edge with one of either red(r) or black(b) color. He is interested in knowing how many triplets(a,b,c) of vertices are there , such that, there is atleast one edge having red color on all the three paths i.e. from vertex a to b, vertex b to c and vertex c to a . Note that

View Solution →

Super Maximum Cost Queries

Victoria has a tree, T , consisting of N nodes numbered from 1 to N. Each edge from node Ui to Vi in tree T has an integer weight, Wi. Let's define the cost, C, of a path from some node X to some other node Y as the maximum weight ( W ) for any edge in the unique path from node X to Y node . Victoria wants your help processing Q queries on tree T, where each query contains 2 integers, L and

View Solution →

Contacts

We're going to make our own Contacts application! The application must perform two types of operations: 1 . add name, where name is a string denoting a contact name. This must store name as a new contact in the application. find partial, where partial is a string denoting a partial name to search the application for. It must count the number of contacts starting partial with and print the co

View Solution →