quicksort in matlab

Here is an implementation of quicksort algorithm in MATLAB:

main.m
function sorted_array = quicksort(input_array)
len = length(input_array);

if len <= 1
    sorted_array = input_array;
    return
end

pivot = input_array(round(len/2));
left = [];
middle = [];
right = [];

for i = 1:len
    if input_array(i) < pivot
        left = [left input_array(i)];
    elseif input_array(i) == pivot
        middle = [middle input_array(i)];
    else
        right = [right input_array(i)];
    end
end

sorted_array = [quicksort(left) middle quicksort(right)];
end
490 chars
26 lines

To use the function, call it with the input array as argument:

main.m
input_array = [5 8 1 3 9 6];
sorted_array = quicksort(input_array);
disp(sorted_array);
88 chars
4 lines

Output:

main.m
1     3     5     6     8     9
32 chars
2 lines

gistlibby LogSnag