Merge Sort: Counting Inversions


Problem Statement :


In an array, arr , the elements at indices i and j (where i < j ) form an inversion if arr[ i ] > arr[ j ]. In other words, inverted elements arr[ i ]  and arr[ j ]  are considered to be "out of order". To correct an inversion, we can swap adjacent elements.


Function Description

Complete the function countInversions in the editor below.

countInversions has the following parameter(s):

int arr[n]: an array of integers to sort
Returns

int: the number of inversions
Input Format

The first line contains an integer, d, the number of datasets.

Each of the next d pairs of lines is as follows:

1. The first line contains an integer, n , the number of elements in arr.
The second line contains n space-separated integers,  arr[ i ].

Constraints

1  <=  d   <=  15
1  <=   n  <=  10^5
1  <=  arr[ i ]  <=  10^7



Solution :



title-img


                            Solution in C :

In C :




#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>
long long int c=0;
void MergeIP(int a[],int l,int r){
	if(l<r){
		int k=(l+r)/2;
		MergeIP(a,l,k);
		MergeIP(a,k+1,r);
		MergeIPcount(a,l,r,k);
	}
}

void MergeIPcount(int a[],int l,int r,int k){
	int *b;    
	b=(int *)malloc(sizeof(int)*(r-l+1));
	int i=l,j=k+1,x=0;
	while(i<=k&&j<=r){
		if(a[i]<=a[j]){
            b[x++]=a[i++];            
        }			
		else if(a[i]>a[j]){
            b[x++]=a[j++];
            c=c+(k-i+1);
        }
        
            
	}	
	while(i<=k)
		b[x++]=a[i++];
	while(j<=r)
		b[x++]=a[j++];
	i=l;
	x=0;
	while(i<=r)
		a[i++]=b[x++];
	free(b);
}
int main(){
    int t; 
    scanf("%d",&t);
    for(int a0 = 0; a0 < t; a0++){
        int n; 
        scanf("%d",&n);
        int *arr = malloc(sizeof(int) * n);
        for(int arr_i = 0; arr_i < n; arr_i++){
           scanf("%d",&arr[arr_i]);
        }
        MergeIP(arr,0,n-1);
        printf("%lld\n",c);
        c=0;
    }
    return 0;
}
                        


                        Solution in C++ :

In  C++ :




#include <map>
#include <set>
#include <list>
#include <cmath>
#include <ctime>
#include <deque>
#include <queue>
#include <stack>
#include <string>
#include <bitset>
#include <cstdio>
#include <limits>
#include <vector>
#include <climits>
#include <cstring>
#include <cstdlib>
#include <fstream>
#include <numeric>
#include <sstream>
#include <iostream>
#include <algorithm>
#include <unordered_map>

using namespace std;
long long contador=0;
typedef vector<int> vi;
vi va, vb, vc;
void combinar(int a, int b)
{
    //vi r;
    int i=a, mitad=(a+b)/2,j=mitad, w=a;
    while (i<mitad and j<b)
    {
        //cout<<"coi\n";
        if (va[i]<=va[j])
        {
            vb[w]=va[i];
            ++i;
        }
        else
        {
            contador += mitad-i;
            //cout<<"aqui\n";
            vb[w]=va[j];
            ++j;
        } 
            ++w;
    }
    while (i<mitad )
    {
        vb[w]=va[i];
        ++i;
        ++w;
    }
    while (j<b)
        {
            //contador += a.size()-i;
            vb[w]=va[j];
            ++j;
        ++w;
        } 
    for (int p=a; p<b; ++p)
        va[p]=vb[p];
    return ;
}

void mergesort(int a, int b)
{
   if (b-a<=1) return;
    //vi i(a.begin(), a.begin() + a.size()/2 );
    //vi d(a.begin() + a.size()/2, a.end() );
    mergesort(a, (a+b)/2);
    mergesort((a+b)/2,b);
    combinar(a, b);
}

long long count_inversions() {
  contador=0;
    vc=vb=va;
    mergesort(0, va.size());
    sort(vc.begin(), vc.end());
    if (vc!=va) 
        for (int co=-1; ;co--)
            vc[co];
    return contador;
}

int main(){
    int t;
    cin >> t;
    for(int a0 = 0; a0 < t; a0++){
        int n;
        cin >> n;
        vector<int> arr(n);
        for(int arr_i = 0;arr_i < n;arr_i++){
           cin >> arr[arr_i];
        }
        va= arr;
        //cout<<"popoku\n";
        cout << count_inversions() << endl;
    }
    return 0;
}
                    


                        Solution in Java :

In Java :



import java.util.*;

class Solution {
    public static long countInversions(int[] a){
        int n = a.length;
        
        // Base Case
        if(n <= 1) {
            return 0;
        }
        
        // Recursive Case
        int mid = n >> 1;
        int[] left = Arrays.copyOfRange(a, 0, mid);
        int[] right = Arrays.copyOfRange(a, mid, a.length);
        long inversions = countInversions(left) + countInversions(right);
        
        int range = n - mid;
        int iLeft = 0;
        int iRight = 0;
        for(int i = 0; i < n; i++) {
            if(
                iLeft < mid 
                && (
                    iRight >= range || left[iLeft] <= right[iRight]
                )
            ) {
                a[i] = left[iLeft++];
                inversions += iRight;
            }
            else if(iRight < range) {
                a[i] = right[iRight++];
            }
        }
        
        return inversions;
    }
  
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int t = scanner.nextInt();
        
        for(int i = 0; i < t; i++){
            int n = scanner.nextInt();
            int[] a = new int[n];
            
            for(int j = 0; j < n; j++){
                a[j] = scanner.nextInt();
            }
            
            System.out.println(countInversions(a));
        }
        
        scanner.close();
    }
}
                    


                        Solution in Python : 
                            
In Python3 :





def merge(a, l, m, h):
    c = []
    i = l
    j = m + 1
    s = 0
    
    while i <= m and j <= h:
        if a[i] > a[j]:
            # there is an inversion
            s += (m - i + 1)
            c.append(a[j])
            j += 1
        else:
            c.append(a[i])
            i += 1
            
    # Adding remaning numbers
    while i <= m:
        c.append(a[i])
        i += 1
    while j <= h:
        c.append(a[j])
        j += 1
        
    
    a[l: h + 1] = c
    
    return s
            

def count(a, l, h):
    if l >= h:
        return 0
    #print(l, h)
    m = l + (h - l) // 2
    s = 0
    s += count(a, l, m)
    s += count(a, m + 1, h)
    
    s += merge(a, l, m, h)
    return s

def count_inversions(a):
    return count(a, 0, len(a) - 1)

t = int(input().strip())
for a0 in range(t):
    n = int(input().strip())
    arr = list(map(int, input().strip().split(' ')))
    print(count_inversions(arr))
                    


View More Similar Problems

Castle on the Grid

You are given a square grid with some cells open (.) and some blocked (X). Your playing piece can move along any row or column until it reaches the edge of the grid or a blocked cell. Given a grid, a start and a goal, determine the minmum number of moves to get to the goal. Function Description Complete the minimumMoves function in the editor. minimumMoves has the following parameter(s):

View Solution →

Down to Zero II

You are given Q queries. Each query consists of a single number N. You can perform any of the 2 operations N on in each move: 1: If we take 2 integers a and b where , N = a * b , then we can change N = max( a, b ) 2: Decrease the value of N by 1. Determine the minimum number of moves required to reduce the value of N to 0. Input Format The first line contains the integer Q.

View Solution →

Truck Tour

Suppose there is a circle. There are N petrol pumps on that circle. Petrol pumps are numbered 0 to (N-1) (both inclusive). You have two pieces of information corresponding to each of the petrol pump: (1) the amount of petrol that particular petrol pump will give, and (2) the distance from that petrol pump to the next petrol pump. Initially, you have a tank of infinite capacity carrying no petr

View Solution →

Queries with Fixed Length

Consider an -integer sequence, . We perform a query on by using an integer, , to calculate the result of the following expression: In other words, if we let , then you need to calculate . Given and queries, return a list of answers to each query. Example The first query uses all of the subarrays of length : . The maxima of the subarrays are . The minimum of these is . The secon

View Solution →

QHEAP1

This question is designed to help you get a better understanding of basic heap operations. You will be given queries of types: " 1 v " - Add an element to the heap. " 2 v " - Delete the element from the heap. "3" - Print the minimum of all the elements in the heap. NOTE: It is guaranteed that the element to be deleted will be there in the heap. Also, at any instant, only distinct element

View Solution →

Jesse and Cookies

Jesse loves cookies. He wants the sweetness of all his cookies to be greater than value K. To do this, Jesse repeatedly mixes two cookies with the least sweetness. He creates a special combined cookie with: sweetness Least sweet cookie 2nd least sweet cookie). He repeats this procedure until all the cookies in his collection have a sweetness > = K. You are given Jesse's cookies. Print t

View Solution →