Task: Given an array of size N, find the inversion count of an array.
Example:
Input:
1
5
2 4 1 3 5
Output:
3
Here is the Code:
Program in C++:
- #include<iostream>
 - #include<bits/stdc++.h>
 - using namespace std;
 - long long int c;
 - void count(long long int *arr,int l,int m,int r)
 - {
 - int n1=m-l+1;
 - int n2=r-m;
 - long long int a[n1],b[n2];
 - for(int i=0;i<n1;i++)
 - {
 - a[i]=arr[l+i];
 - }
 - for(int j=0;j<n2;j++)
 - {
 - b[j]=arr[m+1+j];
 - }
 - int i=0,j=0,k=l;
 - while(i<n1&&j<n2)
 - {
 - if(a[i]<=b[j])
 - {
 - arr[k]=a[i];
 - i++;
 - }
 - else
 - {
 - arr[k]=b[j];
 - j++;
 - c+=n1-i;
 - }
 - k++;
 - }
 - while(i<n1)
 - {
 - arr[k]=a[i];
 - k++,i++;
 - }
 - while(j<n2)
 - {
 - arr[k]=b[j];
 - k++,j++;
 - }
 - }
 - void inversionOfArray(long long int *a,int i,int j)
 - {
 - if(i==j)
 - {
 - return ;
 - }
 - else
 - {
 - int m=floor((i+j)/2);
 - inversionOfArray(a,i,m);
 - inversionOfArray(a,m+1,j);
 - count(a,i,m,j);
 - }
 - }
 - int main()
 - {
 - int t;
 - cin>>t;
 - while(t--)
 - {
 - int n;
 - cin>>n;
 - long long int a[n];
 - for(int i=0;i<n;i++)
 - {
 - cin>>a[i];
 - }
 - c=0;
 - inversionOfArray(a,0,n-1);
 - cout<<c<<endl;
 - }
 - return 0;
 - }
 
Here is the Video:
Comments
Post a Comment