mergesort in matlab

Here's an implementation of mergesort in MATLAB:

main.m
function A = mergesort(A)
    n = length(A);
    if n > 1
        m = floor(n/2);
        left = mergesort(A(1:m));
        right = mergesort(A(m+1:n));
        A = merge(left,right);
    end
end

function C = merge(A,B)
    nA = length(A);
    nB = length(B);
    C = zeros(1,nA+nB);
    i = 1; j = 1; k = 1;
    while i <= nA && j <= nB
        if A(i) <= B(j)
            C(k) = A(i);
            i = i+1;
        else
            C(k) = B(j);
            j = j+1;
        end
        k = k+1;
    end
    while i <= nA
        C(k) = A(i);
        i = i+1; k = k+1;
    end
    while j <= nB
        C(k) = B(j);
        j = j+1; k = k+1;
    end
end
655 chars
35 lines

The mergesort function is implemented recursively. If the length of the input array is greater than 1, the function calls itself on the left half and the right half of the input array, and then merges the two sorted halves using the merge function.

The merge function takes two sorted arrays as input and returns their sorted combination using two while loops that iterate over the length of each array until all elements have been merged in the output array C.

gistlibby LogSnag