用c++的方法给定一个整数数组 A=(a0,a1,…an-1),若 i<j 且 ai>aj,则<ai,aj>就为一 个逆序对。例如数组(3,1,4,5,2)的逆序对有<3,1>,<3,2>,<4,2>, <5,2>。设计一个算法采用蛮力法求 A 中逆序对的个数即逆序数。设计算法求 解逆序对的个数;并且要求用户自己输入数据
时间: 2024-02-26 19:57:55 浏览: 245
好的,以下是用C++实现的蛮力算法和归并排序算法求解逆序对个数的代码:
蛮力算法:
```cpp
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> nums;
int n;
cin >> n;
for(int i = 0; i < n; i++) {
int num;
cin >> num;
nums.push_back(num);
}
int count = 0;
for(int i = 0; i < n - 1; i++) {
for(int j = i + 1; j < n; j++) {
if(nums[i] > nums[j]) {
count++;
}
}
}
cout << count << endl;
return 0;
}
```
归并排序算法:
```cpp
#include <iostream>
#include <vector>
using namespace std;
int merge(vector<int>& nums, int left, int mid, int right) {
int count = 0;
vector<int> temp(right - left + 1);
int i = left, j = mid + 1, k = 0;
while(i <= mid && j <= right) {
if(nums[i] <= nums[j]) {
temp[k++] = nums[i++];
} else {
count += mid - i + 1;
temp[k++] = nums[j++];
}
}
while(i <= mid) {
temp[k++] = nums[i++];
}
while(j <= right) {
temp[k++] = nums[j++];
}
for(int p = 0; p < temp.size(); p++) {
nums[left + p] = temp[p];
}
return count;
}
int mergeSort(vector<int>& nums, int left, int right) {
if(left >= right) {
return 0;
}
int count = 0;
int mid = left + (right - left) / 2;
count += mergeSort(nums, left, mid);
count += mergeSort(nums, mid + 1, right);
count += merge(nums, left, mid, right);
return count;
}
int main() {
vector<int> nums;
int n;
cin >> n;
for(int i = 0; i < n; i++) {
int num;
cin >> num;
nums.push_back(num);
}
int count = mergeSort(nums, 0, n - 1);
cout << count << endl;
return 0;
}
```
两种算法的输入方式都是:第一行输入数组的大小n,第二行输入n个整数作为数组元素。
输出为数组中逆序对的个数。
阅读全文