求数组逆序对数最快的c++代码
时间: 2024-02-11 14:40:07 浏览: 103
C++数组逆序(数组)
以下是基于归并排序的算法,可以在O(nlogn)的时间复杂度内求出数组的逆序对数:
```
#include <stdio.h>
long long merge(int arr[], int left, int mid, int right) {
int i = left, j = mid + 1, k = 0;
long long count = 0;
int temp[right - left + 1];
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 (i = left, k = 0; i <= right; i++, k++) {
arr[i] = temp[k];
}
return count;
}
long long mergeSort(int arr[], int left, int right) {
if (left >= right) {
return 0;
}
int mid = (left + right) / 2;
long long count = 0;
count += mergeSort(arr, left, mid);
count += mergeSort(arr, mid + 1, right);
count += merge(arr, left, mid, right);
return count;
}
long long countInversePairs(int arr[], int n) {
return mergeSort(arr, 0, n - 1);
}
int main() {
int arr[] = { 7, 5, 6, 4 };
int n = sizeof(arr) / sizeof(arr[0]);
long long count = countInversePairs(arr, n);
printf("Number of inverse pairs: %lld\n", count);
return 0;
}
```
阅读全文