我的倒置计数算法有什么问题?
What is wrong with my algorithm for counting inversion?
该代码适用于 {3,3,3,3}、{1,2,3,4}、{2,4,1,3,5} 等测试用例。但它不是'为 {1,20,6,4,5,2,7,3,5} 工作,应该 return 18 次反转。我的代码让我进行了 16 次反转。
class Test{
static int count =0;
public static void main(String[] agrs) {
int[] arr = new int[] {1,20,6,4,5,2,7,3,5};
sort(arr);
System.out.println("\n"+count);
}
private static void sort(int[] arr) {
int length = arr.length;
int tempArr[] = new int[length];
divideAndConquer(arr,tempArr,0,length-1);
}
private static void divideAndConquer(int[] arr, int[] tempArr, int low, int high) {
if(low < high){
int middle = low + (high - low) / 2;
divideAndConquer(arr, tempArr, low, middle);
divideAndConquer(arr, tempArr, middle + 1, high);
merge(arr, tempArr, low, middle, high);
}
}
private static void merge(int[] arr, int[] tempArr, int low, int middle,int high) {
for (int i = low; i <= high; i++)
tempArr[i] = arr[i];
int i = low, j = middle + 1, k = low;
while (i <= middle && j <= high) {
if(tempArr[i] < tempArr[j]) {
arr[k] = tempArr[i];
i++;
}
else {
arr[k] = tempArr[j];
if(tempArr[i] != tempArr[j])
count += middle+1 - i;
System.out.println(count);
j++;
}
k++;
}
while (i <= middle) {
arr[k] = tempArr[i];
k++;
i++;
}
}
}
换行就行了
if(tempArr[i] < tempArr[j]) {
到
if(tempArr[i] <= tempArr[j]) {
问题就迎刃而解了
该代码适用于 {3,3,3,3}、{1,2,3,4}、{2,4,1,3,5} 等测试用例。但它不是'为 {1,20,6,4,5,2,7,3,5} 工作,应该 return 18 次反转。我的代码让我进行了 16 次反转。
class Test{
static int count =0;
public static void main(String[] agrs) {
int[] arr = new int[] {1,20,6,4,5,2,7,3,5};
sort(arr);
System.out.println("\n"+count);
}
private static void sort(int[] arr) {
int length = arr.length;
int tempArr[] = new int[length];
divideAndConquer(arr,tempArr,0,length-1);
}
private static void divideAndConquer(int[] arr, int[] tempArr, int low, int high) {
if(low < high){
int middle = low + (high - low) / 2;
divideAndConquer(arr, tempArr, low, middle);
divideAndConquer(arr, tempArr, middle + 1, high);
merge(arr, tempArr, low, middle, high);
}
}
private static void merge(int[] arr, int[] tempArr, int low, int middle,int high) {
for (int i = low; i <= high; i++)
tempArr[i] = arr[i];
int i = low, j = middle + 1, k = low;
while (i <= middle && j <= high) {
if(tempArr[i] < tempArr[j]) {
arr[k] = tempArr[i];
i++;
}
else {
arr[k] = tempArr[j];
if(tempArr[i] != tempArr[j])
count += middle+1 - i;
System.out.println(count);
j++;
}
k++;
}
while (i <= middle) {
arr[k] = tempArr[i];
k++;
i++;
}
}
}
换行就行了
if(tempArr[i] < tempArr[j]) {
到
if(tempArr[i] <= tempArr[j]) {
问题就迎刃而解了