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

Get Node Value

This challenge is part of a tutorial track by MyCodeSchool Given a pointer to the head of a linked list and a specific position, determine the data value at that position. Count backwards from the tail node. The tail is at postion 0, its parent is at 1 and so on. Example head refers to 3 -> 2 -> 1 -> 0 -> NULL positionFromTail = 2 Each of the data values matches its distance from the t

View Solution →

Delete duplicate-value nodes from a sorted linked list

This challenge is part of a tutorial track by MyCodeSchool You are given the pointer to the head node of a sorted linked list, where the data in the nodes is in ascending order. Delete nodes and return a sorted list with each distinct value in the original list. The given head pointer may be null indicating that the list is empty. Example head refers to the first node in the list 1 -> 2 -

View Solution →

Cycle Detection

A linked list is said to contain a cycle if any node is visited more than once while traversing the list. Given a pointer to the head of a linked list, determine if it contains a cycle. If it does, return 1. Otherwise, return 0. Example head refers 1 -> 2 -> 3 -> NUL The numbers shown are the node numbers, not their data values. There is no cycle in this list so return 0. head refer

View Solution →

Find Merge Point of Two Lists

This challenge is part of a tutorial track by MyCodeSchool Given pointers to the head nodes of 2 linked lists that merge together at some point, find the node where the two lists merge. The merge point is where both lists point to the same node, i.e. they reference the same memory location. It is guaranteed that the two head nodes will be different, and neither will be NULL. If the lists share

View Solution →

Inserting a Node Into a Sorted Doubly Linked List

Given a reference to the head of a doubly-linked list and an integer ,data , create a new DoublyLinkedListNode object having data value data and insert it at the proper location to maintain the sort. Example head refers to the list 1 <-> 2 <-> 4 - > NULL. data = 3 Return a reference to the new list: 1 <-> 2 <-> 4 - > NULL , Function Description Complete the sortedInsert function

View Solution →

Reverse a doubly linked list

This challenge is part of a tutorial track by MyCodeSchool Given the pointer to the head node of a doubly linked list, reverse the order of the nodes in place. That is, change the next and prev pointers of the nodes so that the direction of the list is reversed. Return a reference to the head node of the reversed list. Note: The head node might be NULL to indicate that the list is empty.

View Solution →