Question
Can i please get help with problem 3? please, if possible, answer in a text format.

JN/2) f(n/2); f(n/2); f(n/2); Problem 3. Let A[O...n-1) be an array of n distinct integers. A pair (Ali), A[]) is said to be
0 0
Add a comment Improve this question Transcribed image text
Answer #1

#include<bits/stdc++.h>
using namespace std;
int merge(int a[],int st,int mid,int end)
{
int inv=0;
int temp[end-st+1];
int l=0;
int i=st;
int j=mid+1;
while(i<=mid && j<=end)
{
if(a[i]<a[j])
{
temp[l++]=a[i++];
}
else
{
temp[l++]=a[j++];
inv+=(mid-i+1);
}
}
while(i<=mid)
temp[l++]=a[i++];
while(j<=end)
temp[l++]=a[j++];
for(i=0;i<l;i++)
a[st+i]=temp[i];
return inv;
}
int countInversions(int a[],int st,int end)
{
int inv=0;
if(st<end)
{
int mid=(st+end)/2;
inv=countInversions(a,st,mid);
inv+=countInversions(a,mid+1,end);
inv+=merge(a,st,mid,end);
}
return inv;
}
int main()
{
int n,i;
cin>>n;
int a[n];
for(i=0;i<n;i++)
cin>>a[i];
cout<<countInversions(a,0,n-1);
}

#include<bits/stdc++.h> using namespace std; int merge(int a[], int st, int mid, int end) int inv=0); int temp[end-st+1]; int

Input 5 4 3 2 1 Output

Time Complexity:- O(nlogn)

Please upvote if you found this solution useful and comment for any doubts.

Add a comment
Know the answer?
Add Answer to:
Can i please get help with problem 3? please, if possible, answer in a text format....
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT