# 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 :

```                            ```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;
typedef vector<int> vi;
vi va, vb, vc;
void combinar(int a, int b)
{
//vi r;
{
//cout<<"coi\n";
if (va[i]<=va[j])
{
vb[w]=va[i];
++i;
}
else
{
//cout<<"aqui\n";
vb[w]=va[j];
++j;
}
++w;
}
{
vb[w]=va[i];
++i;
++w;
}
while (j<b)
{
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() {
vc=vb=va;
mergesort(0, va.size());
sort(vc.begin(), vc.end());
if (vc!=va)
for (int co=-1; ;co--)
vc[co];
}

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

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))```
```

## Tree: Postorder Traversal

Complete the postorder function in the editor below. It received 1 parameter: a pointer to the root of a binary tree. It must print the values in the tree's postorder traversal as a single line of space-separated values. Input Format Our test code passes the root node of a binary tree to the postorder function. Constraints 1 <= Nodes in the tree <= 500 Output Format Print the

## Tree: Inorder Traversal

In this challenge, you are required to implement inorder traversal of a tree. Complete the inorder function in your editor below, which has 1 parameter: a pointer to the root of a binary tree. It must print the values in the tree's inorder traversal as a single line of space-separated values. Input Format Our hidden tester code passes the root node of a binary tree to your \$inOrder* func

## 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

## 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.

## 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

## 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 <