算法 逆序对

 题目:给定一个数组,选择数组中的逆序对

arr={5,8,7,6,4}

arr数组中的逆序对:{5,4}、{8,7}、{8,6}、{8,4}、{7,6}、{6,4}

解题思路:如果通过遍历每个数,然后寻找逆序对,主要的时间复制度是O(N^2),通过归并排序的方法寻找逆序对的时间复制度O(NlogN)

import java.util.Arrays;

class Solution {
    public static int getReverse(int[] arr, int l, int r) {
        int reverseNum = 0;
        if (l < r) {
            int mid = (l + r) / 2;
            reverseNum += getReverse(arr, l, mid);
            reverseNum += getReverse(arr, mid + 1, r);
            reverseNum += meger(arr, mid, l, r);
        }
        return reverseNum;
    }


    public static int meger(int[] arr, int mid, int l, int r) {
        int[] temp = new int[r - l + 1];
        int reverseNum = 0;

        int i = l;
        int j = mid + 1;
        int k = 0;

        while (i <= mid && j <= r) {
            if (arr[i] <= arr[j]) {
                temp[k++] = arr[i++];
            } else {
                temp[k++] = arr[j++];
                reverseNum += (mid - i + 1);
            }
        }

        while (i <= mid) {
            temp[k++] = arr[i++];
        }
        while (j <= r) {
            temp[k++] = arr[j++];
        }
        for (int k2 = 0; k2 < temp.length; k2++) {
            arr[k2 + l] = temp[k2];
        }
        return reverseNum;
    }

    public static void main(String[] args) {

        int[] nums = {5, 8, 7, 6, 4};

        int s = Solution.getReverse(nums, 0, nums.length - 1);
        System.out.println(Arrays.toString(nums));
        System.out.println(s);
    }
};

 

posted @ 2016-09-07 15:08  googlemeoften  阅读(630)  评论(0编辑  收藏  举报