[英]Finding number of inversions in given array
I have written the following code to find the inversions in array {1,4,2,5,3} by using merge sort technique.我编写了以下代码,通过使用合并排序技术来查找数组 {1,4,2,5,3} 中的反转。 I have been debugging it to the best of my knoledge but I am not able to find out my mistake (as the output is not expected).
我一直在尽我所能调试它,但我无法找出我的错误(因为 output 不是预期的)。 Kindly help.
请帮忙。
Please note: this is done for educational purposes and is not part of any ongoing contest.请注意:这是出于教育目的,不是任何正在进行的比赛的一部分。
My code:我的代码:
#include<iostream>
#include<vector>
using namespace std;
int merge(int *arr,int l,int m,int r,int n)
{
int temp[n];
long long count =0;
int i=l;
int j=m+1;
while(i<=m and j<=r)
{
if (arr[i-1]>arr[j-1])
{
count += m-i+1;
temp[i+j-m-2] = arr[j-1];
j++;
}
else
{
temp[i+j-m-2] = arr[i-1];
i++;
}
}
if (i>m)
{
for (int k=j;k<=r;k++)
temp[k-1] = arr[k-1];
}
else
{
for (int k=i;k<=m;k++)
temp[k-1] = arr[k-1];
}
for (int k=l;k<=r;k++)
arr[k-1] = temp[k-1];
return count;
}
int inversions(int *arr, int l,int r,int n)
{
if (l<r)
{
int m=(l+r)/2;
return inversions(arr,l,m,n)+inversions(arr,m+1,r,n)+merge(arr,l,m,r,n);
}
return 0;
}
int main()
{
int arr[5] = {1,4,2,5,3};
cout<<inversions(arr,1,5,5)<<endl;
for (int i=1;i<=5;i++)
cout<<arr[i-1]<<" ";
return 0;
}
My expected output:我预期的 output:
3
1 2 3 4 5
Actual output实际output
2
1 4 2 5 0
I am very interested in C++ so I am learning it.我对C++很感兴趣,所以我正在学习它。 It's already 1 year learning C++ so I think I could help you.
学习 C++ 已经 1 年了,所以我想我可以帮助你。 You Have many mistakes but I noticed The actual mistake It's the actual output. I used this code only in educational purposes and that's the mistake.
你有很多错误,但我注意到实际的错误是实际的 output。我仅将此代码用于教育目的,这就是错误。 Your actual output is not correct The actual actual output is: 2 1 4 2 5 264755412
你的实际output不正确实际output是:2 1 4 2 5 264755412
So you can check again your code to see your mistake.所以您可以再次检查您的代码以查看您的错误。 Best REGARDS from Tigran.
Tigran 致以最诚挚的问候。 Country: Armenia |
国家:亚美尼亚 | Region: Yerevan
地区:埃里温
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.