public class Solution { public int InversePairs(int [] array) { if (array == null || array.length < 1) { return 0; } int[] res = new int[1]; mergeSort(array, 0, array.length - 1, res); return res[0]; } private void mergeSort(int[] arr, int l, int r, int[] res) { if (l >= r) { return; } int mid = l + (r - l) / 2; mergeSort(arr, l, mid, res); mergeSort(arr, mid + 1, r, res); merge(arr, l, mid, r, res); } private void merge(int[] arr, int l, int mid, int r, int[] res) { int[] tmp = new int[r - l + 1]; int i = l; int j = mid + 1; int k = 0; while (i <= mid && j <= r) { if (arr[i] > arr[j]) { tmp[k++] = arr[j++]; res[0] += (mid - i + 1); res[0] %= 1000000007; } else { tmp[k++] = arr[i++]; } } while (i <= mid) { tmp[k++] = arr[i++]; } while (j <= r) { tmp[k++] = arr[j++]; } for (k = 0, i = l; i <= r; i++, k++) { arr[i] = tmp[k]; } } }