2

I made Merge sort by using MATLAB.

And I tried to bar - elements' # vs elapsed time.

But the graph is like y=x. Please help me TT

My code is the following

function result = Merge_sort2(input, p, r)
global A;
A = input;
if p < r
    q = floor((p+r)/2);
    Merge_sort2(A, p, q);
    Merge_sort2(A, q+1, r);
    Merge2(p, q, r);
end
result = A;
end

function Merge2(p, q, r)
global A;
n1 = q - p + 1;
n2 = r - q;
L = [];
R = [];
for i = 1 : n1
    L(i) = A(p+i-1);
end

for j = 1 : n2
    R(j) = A(q+j);
end

L(n1+1) = inf;
R(n2+1) = inf;

i = 1;
j = 1;

for k = p : r
    if L(i) <= R(j)
        A(k) = L(i);
        i = i + 1;
    else
        A(k) = R(j);
        j = j + 1;
    end
end
end

And the next code is finding running time code.

function Running_time2(func, incr, num)

y = [];
max = incr * num;

for i = incr : incr : max
    data = i:-1:1;
    len = length(data);

    a = tic;
    res = func(data, 1, len);
    elapsed = toc(a);

    y = [y elapsed];
    fprintf('[The number of elements: %d]\t', i);
    fprintf('[Elapsed time: %fs]\n', elapsed);
end

x = incr : incr: max;
bar(x, y);
end

I typed in the command window in MATLAB.

Running_time2(@Merge_sort2, 10, 300)

the graph result is like this: enter image description here

Danny_Kim
  • 299
  • 2
  • 18
  • have you tried using `profile` to see what is going on? – Shai Sep 21 '15 at 13:28
  • 1
    pre-allocation! see [this thread](http://stackoverflow.com/questions/17424921/matlab-array-growing-inside-a-loop-so-what). – Shai Sep 21 '15 at 13:30
  • @Shai what is profile? Actually, this is my second time using Matlab. (Last time, i made insertion sort using matlab) sorry for my ignorance :( – Danny_Kim Sep 21 '15 at 13:31
  • See [this help on `profile`](http://www.mathworks.com/help/matlab/matlab_prog/profiling-for-improving-performance.html). – Shai Sep 21 '15 at 13:32
  • Aha~ thanks for you to give me the idea what I have to do first. I have to study profiling from now on. – Danny_Kim Sep 21 '15 at 13:39

0 Answers0