0
Я преподаю MATLAB, используя книгу «Insight Through Computing». У меня есть Merge
и функция MergeSortR
в MATLAB. Я хочу расширить функцию MergeSortR
, чтобы подсчитать количество сравнений, которые выполняет функция Merge
. Как мне это сделать? Функции в книге приведены ниже:Как подсчитать количество сравнений в слиянии через MergeSortR (MATLAB)
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
Проблема заключается не в том, что, но проходя каждый подсчитывать в функцию MergeSortR, сохраняя их для каждого вектора и добавления Итого. –