java归并排序解逆序问题

public class test {
    public static void main(String[] args) {
        int[] array = {1,2,3,4,5,6,7,0};
        test test = new test();
        int i = test.InversePairs(array);
        for(int a:array){
            System.out.println(a);
        }
        System.out.println(i);
    }
    public static int count = 0; // 设置一个全局变量来记录逆序的个数
    public int InversePairs(int [] array) {
        if(array.length == 0){
            return 0;
        }
        int [] temp = new int[array.length]; // 外部设置传入数组,可以减少空间复杂度
        return Sort(array,0,array.length-1,temp);
    }
    private int Sort(int [] arry,int start, int end,int [] temp){
        if(start >= end)
            return 0;
        int mid = (start+end)/2;
         Sort(arry,start,mid,temp);
         Sort(arry,mid+1,end,temp);
        return Merge(arry,start,mid,end,temp);
    }
    private int Merge(int [] array, int left,int mid, int right, int[] temp){
        int temp1 = left;
        int temp2 = mid+1;
        int temp3 = 0;
        while (temp1 <= mid && temp2 <= right){
            if(array[temp1] <= array[temp2]){
                temp[temp3++] = array[temp1++];
            }else {
                temp[temp3++] = array[temp2++];
                count += temp2-temp1-1;  // 这次交换改变的逆序个数
            }
        }
        while (temp1<=mid){
            temp[temp3++] = array[temp1++];
        }
        while (temp2<=right){
            temp[temp3++] = array[temp2++];
        }
        int i = 0;                          // 把有序数组存回原数组
        while (left<=right){
            array[left++] = temp[i++];
        }
        return count;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_38846089/article/details/85857200