【发布时间】:2019-05-09 02:05:21
【问题描述】:
我正在编写一个 C++ 程序,它使用归并排序来查找向量中的反转数。当i'th 元素大于j'th 元素时会发生反转,其中i < j。例如,假设向量是{ 1, 3, 5, 2 },那么有2个反转:{3,2}和{5,2}。
countNsort 函数不断递归和分割向量,直到子向量的长度只有一个元素。 countNsortSplit 函数执行归并排序来排序和计数倒置的次数。
我试过了:
- 初始化输入向量的不同方法。
vector<int> a{2,1};、vector<int> a; a={2,1};和vector<int> a(2); a={2,1};。 - 将输入向量拆分为子向量的不同方法。
vector<int> c(a.begin()+half, a.begin()+n);和vector<int> c(a.begin()+half, a.end());,其中 n 是向量的大小。 - 不同的 IDE。 Atoms 给了我这个:
bash: line 1: 13763 Segmentation fault: 11 /tmp/cpp.out [Finished in 20.57s],CodeBlocks 给了我这个:error: expected expression这条线:a={2,1}:。
#include <stdio.h>
#include <vector>
#include <iostream>
using namespace std;
struct returnVal {
int count;
vector<int> sorted_array;
};
returnVal countNsortSplit(vector<int> left, vector<int> right, int n) {
returnVal output;
int count = 0;
vector<int> merge;
int i = 0;
int j = 0;
for (int k = 0; k < n; k++) {
if (left[i] < right[j]) {
merge[k] = left[i];
i++;
} else {
merge[k] = right[j];
j++;
// increment count by the # of remaining elements in left
count += left.size()-i;
}
}
output.sorted_array = merge;
output.count = count;
return output;
}
returnVal countNsort(vector<int> a, int n) {
returnVal output;
if (n == 1) {
output.sorted_array = a;
output.count = 0;
return output;
} else {
returnVal left;
returnVal right;
returnVal split;
int half = n / 2;
vector<int> b(a.begin(), a.begin() + half);
vector<int> c(a.begin() + half, a.begin() + n);
left = countNsort(b, half);
right = countNsort(c, n - half); // need n-n/2 in case of odd length
split = countNsortSplit(left.sorted_array, right.sorted_array, n);
output.sorted_array = split.sorted_array;
output.count = left.count + right.count + split.count;
return output;
}
}
int main() {
vector<int> a(2);
//a = {1,3,5,2};
//a = {1,3,5,2,4,6};
a = {2, 1};
returnVal result;
result = countNsort(a, a.size());
cout << result.count << endl;
}
【问题讨论】:
-
附加信息:当第 i 个元素大于第 j 个元素时发生反转,其中 i
-
您在这里调用 undefined behavior
merge[k]您必须先调整向量的大小,然后才能使用索引运算符访问它。也不要在 cmets 中添加其他信息。你可以随时edit你的问题。 -
提示:
std::vector在初始化时大小为零。添加元素:push_back或emplace_back。对于固定大小:std::array. -
推荐使用 asan 或 valgrind 运行此类程序。他们有时会在段错误实际出现之前更早地发现问题。 YMMV