下面是我对数组反转的实现。对于某些输入,它会产生所需的结果。例如:
1 : 0,1,2,3,4,5,6,7,8,9 -> 0 反转(正确)
2 : 1000,999,998,997,.......3,2,1 -> 499500 反转(正确)
3 : 1,3,5,2,4,6 -> 3 反转(正确)
但对于
4 : 9,10,8,1,4,7,6,2,5,3 -> 41 反转(不正确)。正确答案是 33。
public class Assignment1 {
static int[] result = new int[10];
public static long divideW (int Arr[]) {
long countLeft ;
long countRight ;
long countMerge ;
int mid = (Arr.length)/2;
if (Arr.length <= 1)
return 0;
else
{
int leftArr[] = new int [mid];
int rightArr[] = new int [Arr.length - mid];
for (int i = 0; i < mid; i++){
leftArr[i] = Arr[i];
}
for (int j = 0; j < rightArr.length ; j++){
rightArr[j] = Arr[mid + j];
}
countLeft = divideW (leftArr);
countRight = divideW (rightArr);
//int[] result = new int[Arr.length];
countMerge = conquer(leftArr, rightArr, result);
return (countLeft + countRight + countMerge);
}
}
public static long conquer (int []l, int[]r, int[] result) {
int i = 0;
int j = 0;
int k = 0;
long count = 0;
while ((i < l.length) && (j < r.length)) {
if (l[i] <= r [j]) {
result[k] = l[i++];
}
else if (l[i] > r[j]) {
result[k] = r[j++];
count += l.length - i;
}
++k;
}
while ( i < l.length) {
result[k++] = l[i++];
}
while ( j < r.length) {
result[k++] = r[j++];
}
return count;
}
public static void main(String[] args) {
Assignment1 rs = new Assignment1();
int anArr[] = {9,10,8,1,4,7,6,2,5,3};
System.out.println (rs.divideW(anArr));
for (int i = 0 ; i < result.length; ++i) {
System.out.println (result[i]);
}
}
}