#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 count = 0;
while (i <= mid && j <= right) {
if (arr[i] <= arr[j]) {
temp[k++] = arr[i++];
} else {
temp[k++] = arr[j++];
count += mid - i + 1;
}
}
while (i <= mid) {
temp[k++] = arr[i++];
}
while (j <= right) {
temp[k++] = arr[j++];
}
for (int m = left; m <= right; m++) {
arr[m] = temp[m];
}
return count;
}
int mergeSort(int arr[], int temp[], int left, int right) {
int count = 0;
if (left < right) {
int mid = (left + right) / 2;
count += mergeSort(arr, temp, left, mid);
count += mergeSort(arr, temp, mid + 1, right);
count += merge(arr, temp, left, mid, right);
}
return count;
}
int main() {
int arr[] = {2, 4, 3, 1, 5, 6};
int n = sizeof(arr) / sizeof(arr[0]);
int temp[n];
int count = mergeSort(arr, temp, 0, n - 1);
printf("逆序对个数:%d\n", count);
return 0;
}