c++归并排序逆序对
时间: 2023-12-02 19:43:25 浏览: 108
C++求逆序对的方法
5星 · 资源好评率100%
以下是C++中使用归并排序求逆序对的代码示例:
```c++
#include <iostream>
using namespace std;
long long merge(int arr[], int temp[], int left, int mid, int right) {
int i = left; // 左子数组的起始下标
int j = mid + 1; // 右子数组的起始下标
int k = left; // 合并后数组的起始下标
long long 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 (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 (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;
}
long long getInversePairs(int arr[], int n) {
int *temp = new int[n];
long long count = mergeSort(arr, temp, 0, n - 1);
delete[] temp;
return count;
}
int main() {
int arr[] = { 7, 5, 6, 4 };
int n = sizeof(arr) / sizeof(arr[0]);
long long count = getInversePairs(arr, n);
cout << "逆序对的数量为:" << count << endl;
return 0;
}
```
阅读全文