quick sort in matlab

Here is an implementation of the QuickSort algorithm in MATLAB:

main.m
function arr = quicksort(arr)
% Sort the array arr using quicksort algorithm

    if length(arr) <= 1
        return
    end

    % Choose pivot element
    pivot = arr(end);   
    % Rearrange elements
    i = 1;
    for j = 1:length(arr)-1
        if arr(j) < pivot
            % swap arr(i) and arr(j)
            temp = arr(i);
            arr(i) = arr(j);
            arr(j) = temp;
            i = i + 1;
        end
    end
    % swap arr(i) and arr(end)
    temp = arr(i);
    arr(i) = arr(end);
    arr(end) = temp;
    
    % Recursion
    arr(1:i-1) = quicksort(arr(1:i-1));
    arr(i+1:end) = quicksort(arr(i+1:end));
end
634 chars
30 lines

Here's how you can use it to sort an array:

main.m
>> arr = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5];
>> arr = quicksort(arr);
>> arr

ans =

     1     1     2     3     3     4     5     5     5     6     9
151 chars
8 lines

gistlibby LogSnag