对于我发送给它的一些输入,该算法会返回一个错误。我先用数组写了merge_sort和inversion_count;这给出了正确数量的反转。一旦我转换到向量,我就会收到以下输入:2 4 1 3 5
一双新鲜的眼睛将不胜感激。
vector<int> a;
object o;
length = a.size();
inv = o.count_inversion(a, 0, length-1);
int inversion::merge_and_count(vector<int> vector1, int alpha, int omega)
{
int inversion = 0;
int mid = (alpha + omega) / 2;
int i = alpha;
int j = mid + 1;
int lastITR = 0;
vector<int> final(omega - alpha + 1);
while (i <= mid && j <= omega) {
if (vector1[i] <= vector1[j])
{
final[lastITR++] = vector1[i++];
}
else
{
final[lastITR++] = vector1[j++];
inversion += mid - i + 1;
}
}
while (i <= mid)
{
{
final[lastITR++] = vector1[i++];
}
while (j <= omega)
{
final[lastITR++] = vector1[j++];
}
for (int k=0 ; k < omega-alpha+1; k++)
{
vector1[k+alpha] = final[k];
}
return inversion;
}
int inversion::count_inversion(vector<int> vector1, int a, int b)
{
int x, y, z, mid;
if (a >= b)
{
return 0;
}
mid = (a+b)/2;
x = count_inversion(vector1, a, mid);
y = count_inversion(vector1, mid+1, b);
z = merge_and_count(vector1, a, b);
return x + y + z;
}