如何通过MergeSortR(MATLAB)计算合并中的比较数

时间:2015-02-26 01:22:32

标签: matlab sorting recursion mergesort

我使用" 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

1 个答案:

答案 0 :(得分:0)

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

例如: 而......     ...     算上++     ... 端