# 归并排序的扩展问题

proheart

## 小和问题

1左边比1小的数，没有；
3左边比3小的数，1；
4左边比4小的数，1，3；
2左边比2小的数，1；
5左边比5小的数，1，3，4，2；

``````public class SmallSum {
static int smallSum(int[] arr) {
if (arr == null || arr.length < 2) return 0;
return process(arr, 0, arr.length - 1);
}
// 在arr[left,right]上既要排好序，又要求小和
private static int process(int[] arr, int left, int right) {
if (left >= right) return 0;
int mid = left + (right - left) / 2;
return process(arr, left, mid) + process(arr, mid + 1, right) + merge(arr, left, mid, right);
}

private static int merge(int[] arr, int left, int mid, int right) {
int[] help = new int[right - left + 1];
int i = 0, a = left, b = mid + 1;
int res = 0;
while (a <= mid && b <= right) {
if (arr[a] < arr[b]) res += (right - b + 1) * arr[a];
help[i++] = arr[a] < arr[b] ? arr[a++] : arr[b++];
}
while (b <= right) {
help[i++] = arr[b++];
}
while (a <= mid) {
help[i++] = arr[a++];
}
for (i = 0; i < help.length; i++) {
arr[left + i] = help[i];
}
return res;
}

public static void main(String[] args) {
int[] arr = {1, 3, 4, 2, 5};
System.out.println(smallSum(arr));
}
}``````

## 逆序对问题

``````public class ReversePair {
public static int reversePairs(int[] arr) {
if (arr == null || arr.length < 2) return 0;
int[] copy = new int[arr.length];
for (int i = 0; i < arr.length; i++) copy[i] = arr[i];
return reversePairs(copy, 0, arr.length - 1);
}

// arr[left, right]计算逆序对个数并排序
private static int reversePairs(int[] arr, int left, int right) {
if (left == right) return 0;
int mid = left + (right - left) / 2;
int leftCount = reversePairs(arr, left, mid);
int rightCount = reversePairs(arr, mid + 1, right);
int mergeCount = merge(arr, left, mid, right);
return leftCount + rightCount + mergeCount;
}

private static int merge(int[] arr, int left, int mid, int right) {
int i = 0, a = left, b = mid + 1;
int[] help = new int[right - left + 1];
int res = 0;
while (a <= mid && b <= right) {
if (arr[a] > arr[b]) res += mid - a + 1;
help[i++] = arr[b] < arr[a] ? arr[b++] : arr[a++];
}
while (a <= mid) {
help[i++] = arr[a++];
}
while (b <= right) {
help[i++] = arr[b++];
}
for (i = 0; i < help.length; i++) {
arr[left + i] = help[i];
}
return res;
}
}``````

##### 来刷算法
Learn data structure and algorithm using java.
##### proheart

Developer, Java & Android

38 声望
20 粉丝
0 条评论