public static int countinv(int[] arr, int low, int high){
if(low>=high){
return 0;
}
int mid= (low+high)/2;
int leftans= countinv(arr, low, mid);
int rightans= countinv(arr, mid+1, high);
int split= mergeandcount(arr,low,mid,high);
return leftans+rightans+split;
}
private static int mergeandcount(int[] arr, int low, int mid, int high) {
int[] temp = new int[high-low+1];
int k=0;int count =0;
int i=low; int j= mid+1;
while(i< mid&& j<high){
if(arr[i]<=arr[j]){
temp[k++]=arr[i++];
}
else{
temp[k++]=arr[j++];
count += mid-i;
}
}
while(i<mid){
temp[k++]=arr[i++];
}
while(j<high){
temp[k++]=arr[j++];
} i=low;j=0;k=0;
while(i<high){
arr[i++]=temp[k++];
}
return count;
}
请帮我识别出反转次数的逻辑错误。 它与geeksforgeeks几乎相同。但是我找不到一个。
如建议的那样,主要方法如下: `
public static void main(String[] args) {
int arr[] = {3,2,1};
int j = countinv(arr,0,arr.length);
System.out.println(j);
}
在这种情况下,输出应为3。 它是倒数计数的问题。