【问题标题】:Counting Inversions in MATLAB Using MergeSort在 MATLAB 中使用 MergeSort 计算倒数
【发布时间】:2015-07-22 08:01:59
【问题描述】:

我正在尝试使用 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

【问题讨论】:

  • 反转对是左侧元素大于右侧元素的反转对。例如,[5, 4, 3, 1] 有 6 个反转对:(5, 4), (5, 3), (5, 1), (4, 3), (4, 1) 和 (3, 1)。 python 存在类似的代码,但我似乎无法将其正确转换为 MATLAB。

标签: matlab mergesort counting inversion


【解决方案1】:

好的,所以一个朋友帮我弄清楚了。我的直觉是正确的,但我需要一位实际程序员的帮助才能了解我哪里出错了:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-08
    • 2021-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-29
    • 2017-08-15
    • 2021-03-11
    相关资源
    最近更新 更多