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

Jenny's Subtrees

Jenny loves experimenting with trees. Her favorite tree has n nodes connected by n - 1 edges, and each edge is ` unit in length. She wants to cut a subtree (i.e., a connected part of the original tree) of radius r from this tree by performing the following two steps: 1. Choose a node, x , from the tree. 2. Cut a subtree consisting of all nodes which are not further than r units from node x .

View Solution →

Tree Coordinates

We consider metric space to be a pair, , where is a set and such that the following conditions hold: where is the distance between points and . Let's define the product of two metric spaces, , to be such that: , where , . So, it follows logically that is also a metric space. We then define squared metric space, , to be the product of a metric space multiplied with itself: . For

View Solution →

Array Pairs

Consider an array of n integers, A = [ a1, a2, . . . . an] . Find and print the total number of (i , j) pairs such that ai * aj <= max(ai, ai+1, . . . aj) where i < j. Input Format The first line contains an integer, n , denoting the number of elements in the array. The second line consists of n space-separated integers describing the respective values of a1, a2 , . . . an .

View Solution →

Self Balancing Tree

An AVL tree (Georgy Adelson-Velsky and Landis' tree, named after the inventors) is a self-balancing binary search tree. In an AVL tree, the heights of the two child subtrees of any node differ by at most one; if at any time they differ by more than one, rebalancing is done to restore this property. We define balance factor for each node as : balanceFactor = height(left subtree) - height(righ

View Solution →

Array and simple queries

Given two numbers N and M. N indicates the number of elements in the array A[](1-indexed) and M indicates number of queries. You need to perform two types of queries on the array A[] . You are given queries. Queries can be of two types, type 1 and type 2. Type 1 queries are represented as 1 i j : Modify the given array by removing elements from i to j and adding them to the front. Ty

View Solution →

Median Updates

The median M of numbers is defined as the middle number after sorting them in order if M is odd. Or it is the average of the middle two numbers if M is even. You start with an empty number list. Then, you can add numbers to the list, or remove existing numbers from it. After each add or remove operation, output the median. Input: The first line is an integer, N , that indicates the number o

View Solution →