#include <stdio.h>
int merge(int arr[], int temp[], int left, int mid, int right) {
int i = left;
int j = mid + 1;
int k = left;
int inversions = 0;
while (i <= mid && j <= right) {
if (arr[i] <= arr[j]) {
temp[k++] = arr[i++];
} else {
inversions += (mid - i + 1);
temp[k++] = arr[j++];
}
}
while (i <= mid) {
temp[k++] = arr[i++];
}
while (j <= right) {
temp[k++] = arr[j++];
}
for (int x = left; x <= right; x++) {
arr[x] = temp[x];
}
return inversions;
}
int mergeSort(int arr[], int temp[], int left, int right) {
int inversions = 0;
if (left < right) {
int mid = (left + right) / 2;
inversions += mergeSort(arr, temp, left, mid);
inversions += mergeSort(arr, temp, mid + 1, right);
inversions += merge(arr, temp, left, mid, right);
}
return inversions;
}
int main() {
int arr[]={4,3,9,15,87,7};
int inversions = mergeSort(arr, 6, 0, 5);
printf("逆序对数目为: %d\n", inversions);
return 0;
}