Java 为什么全局声明count变量会为数组的反转计数生成错误的o/p?
这是用于计算要排序的数组的反转数的代码。当count变量在合并期间被全局声明并每次更新时,它会生成错误的o/p。Java 为什么全局声明count变量会为数组的反转计数生成错误的o/p?,java,arrays,sorting,mergesort,Java,Arrays,Sorting,Mergesort,这是用于计算要排序的数组的反转数的代码。当count变量在合并期间被全局声明并每次更新时,它会生成错误的o/p。 class Inversion_of_Array { // arr[]: Input Array // N : Size of the Array arr[] static long count=0L; static long inversionCount(long arr[], long N) { // Your Code H
class Inversion_of_Array
{
// arr[]: Input Array
// N : Size of the Array arr[]
static long count=0L;
static long inversionCount(long arr[], long N)
{
// Your Code Here
if(N==1)
return 0L;
countInversions(arr,0,arr.length-1);
return count;
}
public static void countInversions(long[] a,int low,int high)
{
if(low<high)
{
int mid=low+(high-low)/2;
countInversions(a,low,mid);
countInversions(a,mid+1,high);
crossInversions(a,low,mid,high);
}
}
public static void crossInversions(long a[],int low,int mid,int high)
{
int n1=mid-low+1;
int n2=high-mid;
long l[]=new long[n1];
long r[]=new long[n2];
for(int i=0;i<n1;i++)
l[i]=a[low+i];
for(int i=0;i<n2;i++)
r[i]=a[mid+1+i];
int left=0,right=0,k=low;
while(left<n1 && right<n2)
{
if(l[left]<=r[right])
a[k++]=l[left++];
else
{
count+=(n1-left);
a[k++]=r[right++];
}
}
while(left<n1)
a[k++]=l[left++];
while(right<n2)
a[k++]=r[right++];
}
}
数组的类反转
{
//arr[]:输入数组
//N:数组arr[]的大小
静态长计数=0L;
静态长反转计数(长arr[],长N)
{
//你的代码在这里
如果(N==1)
返回0升;
倒计数(arr,0,arr.length-1);
返回计数;
}
公共静态无效计数反转(长[]a,整数低,整数高)
{
if(low)在
count+=(n1左)中,您仅在最上面的代码样本的一行中更改count
;
。然后在方法中返回该全局变量。显然,两个代码示例并不相等,因为它们计算的内容大不相同。但每次我们合并两个子数组时,都会调用merge方法,这就是我们计算所需交换数目的原因。您只需在topmos中的一行中更改count
t code sample,在count+=(n1左);
中,然后在方法中返回该全局变量。显然,两个代码示例并不相等,因为它们的计数差别很大。但每次我们合并两个子数组时,都会调用merge方法,这就是为什么,当我们计算所需的交换数时。
class Inversion_of_Array
{
// arr[]: Input Array
// N : Size of the Array arr[]
static long inversionCount(long arr[], long N)
{
// Your Code Here
if(N==1)
return 0L;
return countInversions(arr,0,arr.length-1);
}
public static long countInversions(long[] a,int low,int high)
{
long count=0;
if(low<high)
{
int mid=low+(high-low)/2;
count+=countInversions(a,low,mid);
count+=countInversions(a,mid+1,high);
count+=crossInversions(a,low,mid,high);
}
return count;
}
public static long crossInversions(long a[],int low,int mid,int high)
{
int n1=mid-low+1;
int n2=high-mid;
long l[]=new long[n1];
long r[]=new long[n2];
for(int i=0;i<n1;i++)
l[i]=a[low+i];
for(int i=0;i<n2;i++)
r[i]=a[mid+1+i];
long ans=0;
int left=0,right=0,k=low;
while(left<n1 && right<n2)
{
if(l[left]<=r[right])
a[k++]=l[left++];
else
{
ans+=(n1-left);
a[k++]=r[right++];
}
}
while(left<n1)
a[k++]=l[left++];
while(right<n2)
a[k++]=r[right++];
return ans;
}
}