我选用n=6,arr[]={5,4,2,6,3,1}测试下面代码的结果时发现一开始根本没法输出结果,后来变成0,答案则是11,一时没弄明白这串Java代码的问题在哪里
我刚开始以为是static的关系,程序直接输出的是一开始在Nixudui类里的静态初始值0,然后我尝试删除static发现程序不能运行(main里不能引用Nixudui类里的非静态变量)
彻底没辙了
package org.example;
import java.util.Scanner;
class Nixudui{
static int n;
static int count=0;
static int[] arr=new int[110];
static int[] temp=new int[110];
static public void counter(int low,int high){
if(low>=high)
{
return;
}
int mid=(low+high)>>1;
int i=low;int j=mid+1;int t=0;
while(i<=mid&&j<=high){
if(arr[i]>arr[j])
{
temp[t++]=arr[j++];
count=count+mid+1-i;
}
else
{
temp[t++]=arr[i++];
}
}
while(i<=mid)
{
temp[t++]=arr[i++];
}
while(j<=high)
{
temp[t++]=arr[j++];
}
for(int k=0;k<=n-1;k++)
{
arr[low+k]=temp[k];
}
}
}
class Main{
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
Nixudui.n = scanner.nextInt();
for(int i = 0; i < Nixudui.n; i=i+1){ // 修改为 i < nixudui.n 避免数组越界
Nixudui.arr[i] = scanner.nextInt();
}
Nixudui.counter(0, Nixudui.n - 1);
System.out.println(Nixudui.count);
}
}