请用C语言写一个 找到一个数组中逆序对 的代码
时间: 2024-05-02 09:17:16 浏览: 88
以下是使用归并排序的方法,在 C 语言中找到一个数组中逆序对的代码:
```
#include <stdio.h>
int merge(int arr[], int temp[], int left, int mid, int right)
{
int i, j, k;
int count = 0;
i = left;
j = mid;
k = left;
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;
}
int _mergeSort(int arr[], int temp[], int left, int right)
{
int mid, count = 0;
if (right > left) {
mid = (right + left) / 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 countSwaps(int arr[], int n)
{
int temp[n];
return _mergeSort(arr, temp, 0, n - 1);
}
int main()
{
int arr[] = { 1, 20, 6, 4, 5 };
int n = sizeof(arr) / sizeof(arr[0]);
printf("Number of swaps is %d \n", countSwaps(arr, n));
return 0;
}
```
这段代码中,`merge()` 函数用于合并两个有序数组并计算逆序对数目,`_mergeSort()` 函数用于归并排序,并调用 `merge()` 函数计算逆序对数目,`countSwaps()` 函数用于对外暴露接口,以便调用计算逆序对数目的函数。
阅读全文