剑指Offer第36题—Java版

本题使用归并排序的思想,结合归并排序,写出的算法解。

//数组中的逆序对
public static int InversePairs(int[] array){
    if(array==null||array.length<=1)
        return 0;
    int[] copy = new int[array.length];
    //复制原数组
    copy = Arrays.copyOf(array, array.length);
    return mergeCount(array, copy, 0, array.length-1);
}

public static int mergeCount(int[] array, int[] copy, int start, int end){
    if(start==end){
        copy[start] = array[start];
        return 0;
    }
    int mid = (start+end)>>1;
    int leftCount = mergeCount(copy, array, start, mid);
    int rightCount = mergeCount(copy, array, mid+1, end);
    
    //计算两个已经求解好的数组的逆序对
    int i = mid;//i初始化为前半段最后一个数字的下标
    int j = end;//j初始化为后半段最后一个数字的下标
    //作为复制到临时数组的下标
    int index = end;//辅助数组复制的数组的最后一个数字的下标
    //计算两个数组在合并过程中的逆序对数
    int count = 0;//计数--逆序对的数目
    while(i>=start&&j>=mid+1){
        if(array[i]>array[j]){
        	//copy数组存放排序好的数,
            copy[index--] = array[i--];
            count += j-mid;
        }else{
            copy[index--] = array[j--];
        }
    }
    //把左边剩下的放到copy数组
    for(;i>=start;i--){
        copy[index--] = array[i];
    }
    //把右边剩下的放到copy数组
    for(;j>=mid+1;j--){
        copy[index--] = array[j];
    }
    //返回的是某一边的数
    return leftCount+rightCount+count;
}


原文地址:https://www.cnblogs.com/loren-Yang/p/7466140.html