0

MergeSort を使用して MATLAB で反転カウンターを実装しようとしていますが、何らかの理由で、いくつかの答えが間違っています。たとえば、[3, 4, 8, 1] の反転数は 3 ですが、2 になっています。ただし、配列は正しくソートされているので、分割反転のカウント方法はが問題です。

これが私のコードです:

function [count, sorted] = mergesort(A)
% count is the number of inversions; sorted is the sorted array.

n = length(A);
if n == 1
    count = 0;
    sorted = A;
else
    m = ceil(n/2);
    [count1, sorted1] = mergesort(A(1:m));
    [count2, sorted2] = mergesort(A(m+1:n));
    [crosscount, sorted] = merge(sorted1, sorted2);
    count = count1 + count2 + crosscount;
end
end

function [crosscount, z] = merge(x, y)

n = length(x); m = length(y); z = zeros(1, n+m);
ix = 1;
iy = 1;
crosscount = 0;
for iz = 1:(n+m);
    if ix > n
        z(iz) = y(iy);
        iy = iy + 1;
    elseif iy > m
        z(iz) = x(ix);
        ix = ix + 1;
        crosscount = crosscount + (n + 1 - ix); %this might be wrong
    elseif x(ix) <= y(iy)
        z(iz) = x(ix);
        ix = ix + 1;
    elseif x(ix) > y(iy)
        z(iz) = y(iy);
        iy = iy + 1;
        crosscount = crosscount + 1; %im pretty sure this is right
    end
end
end
4

1 に答える 1