Count Inversions in an array - C++
Tue Mar 04 2025 01:53:32 GMT+0000 (Coordinated Universal Time)
Saved by
@Rohan@99
#include <iostream>
#include <vector>
using namespace std;
int Merge(int a[], int low, int mid, int high)
{
vector<int> temp;
int i = low, j = mid+1;
int inversion = 0;
while(i <= mid && j <= high)
{
if(a[i] <= a[j])
{
temp.push_back(a[i]);
++i;
}
else
{
temp.push_back(a[j]);
++j;
inversion += (mid - i + 1);
}
}
while(i <= mid)
{
temp.push_back(a[i]);
++i;
}
while(j <= high)
{
temp.push_back(a[j]);
++j;
}
for(int i = low; i <= high; ++i)
a[i] = temp[i-low];
return inversion;
}
int MergeSort(int a[], int low, int high)
{
if(low == high)
return 0;
int mid = (low+high) / 2;
int inversionCount = 0;
inversionCount += MergeSort(a, low, mid);
inversionCount += MergeSort(a, mid+1, high);
inversionCount += Merge(a, low, mid, high);
return inversionCount;
}
int main()
{
int n;
cin >> n;
int a[n];
for(int i = 0; i < n; ++i)
cin >> a[i];
cout << MergeSort(a, 0, n-1);
return 0;
}
content_copyCOPY
Comments