c语言求逆序数代码
时间: 2023-12-19 18:28:25 浏览: 144
以下是一个使用归并排序求逆序数的 C 代码:
```c
#include <stdio.h>
long long merge(int arr[], int temp[], int left, int mid, int right) {
int i = left, j = mid, k = left;
long long count = 0;
while (i <= mid - 1 && j <= right) {
if (arr[i] <= arr[j]) {
temp[k++] = arr[i++];
} else {
temp[k++] = arr[j++];
count += mid - i;
}
}
while (i <= mid - 1) {
temp[k++] = arr[i++];
}
while (j <= right) {
temp[k++] = arr[j++];
}
for (i = left; i <= right; i++) {
arr[i] = temp[i];
}
return count;
}
long long mergeSort(int arr[], int temp[], int left, int right) {
long long count = 0;
if (right > left) {
int mid = (left + right) / 2;
count += mergeSort(arr, temp, left, mid);
count += mergeSort(arr, temp, mid + 1, right);
count += merge(arr, temp, left, mid + 1, right);
}
return count;
}
int main() {
int arr[] = { 1, 20, 6, 4, 5 };
int n = sizeof(arr) / sizeof(arr[0]);
int temp[n];
long long count = mergeSort(arr, temp, 0, n - 1);
printf("Number of inversions are %lld \n", count);
return 0;
}
```
阅读全文