0

I'm trying to implement an inversion counter in MATLAB using MergeSort, but for some reason, some of the answers are way off. For example, the number of inversions in [3, 4, 8, 1] is 3, but I'm getting 2. However, the array is being sorted correctly, so I think that the way that I'm counting the split inversions is the problem.

Here's my code:

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
  • An inversion pair is one where the element on the left is greater than the element on the right. For example, [5, 4, 3, 1] has 6 inversion pairs: (5, 4), (5, 3), (5, 1), (4, 3), (4, 1) and (3, 1). Similar codes exist for python, but I can't seem to translate that over properly into MATLAB. – Apratim Vidyarthi Jul 22 '15 at 08:13

1 Answers1

0

Alright, so a friend helped me figure it out. My intuition was correct, but I needed help from an actual programmer to understand where I went wrong:

elseif iy > m
        z(iz) = x(ix);
        ix = ix + 1;
        crosscount = crosscount + (n + 1 - ix); **%this might be wrong - this is actually wrong, since you don't want to count if you're traversing beyond the edge of the right array, and since the actual counting is happening in the last if case**
    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 + **(n + 1 - ix)** **this is right because you're counting the remaining numbers in your left array that are also greater than y(iy) and just adding that to your count**
    end