【问题标题】:How to count the number of Comparisons in Merge through MergeSortR (MATLAB)如何通过 MergeSortR (MATLAB) 计算 Merge 中的比较次数
【发布时间】:2015-02-26 01:22:32
【问题描述】:

我正在使用“Insight Through Computing”一书自学 MATLAB。我在 MATLAB 中有一个 Merge 和一个 MergeSortR 函数。我想扩展MergeSortR 函数来计算Merge 函数进行的比较次数。我该怎么做呢?书中的功能如下:

function w = Merge(u,v)
% u and v are column vectors and w is their merge.
n = length(u); m = length(v); w = zeros(n+m,1);
i = 1; % The index of the next u-value to select.
j = 1; % The index of the next v-value to select.
k = 1; % The index of the next w-component to fill.

while i<=n && j<=m
    % u and v have not been exhausted...
    if u(i) <= v(j)
        w(k) = u(i); i = i+1; k = k+1;
    else
        w(k) = v(j); j = j+1; k = k+1;
    end
end
% If any elements in u remain, then copy them into w...
while i<=n 
    w(k) = u(i); i = i+1; k = k+1;
end
% If any elements in v remain, then copy them into w...
while j<=m
    w(k) = v(j); j = j+1; k = k+1;
end 

function y = MergeSortR(x)
% x is a column N-vector.
% y is a column N-vector consisting of the values in x sorted
% from smallest to largest.
N = length(x);
if N==1
    y = x;
else
    m = floor(N/2); 
    % Sort the first half...
    y1 = MergeSortR(x(1:m));
    % Sort the second half...
    y2 = MergeSortR(x(m+1:N));
    % Merge...
    y = Merge(y1,y2);
end

【问题讨论】:

    标签: matlab sorting recursion mergesort


    【解决方案1】:

    您可以在比较循环中使用计数器变量。

    例如: 尽管 ... ... 计数++ ... 结束

    【讨论】:

    • 问题不在于,而是将每个计数传递给 MergeSortR 函数,为每个向量存储它们,然后将总数相加。
    猜你喜欢
    • 2019-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多