quick sort from scratch in matlab

Here's an implementation of Quick Sort algorithm in MATLAB:

main.m
function arr = quicksort(arr)
    n = length(arr);
    
    % Base case: if array has one or fewer elements, return array
    if n < 2
        return
    end
    
    % Choose a pivot value
    pivot = arr(ceil(rand()*n));
    
    % Partition the array around the pivot value
    left = arr(arr < pivot);
    equal = arr(arr == pivot);
    right = arr(arr > pivot);
    
    % Recursively sort the left and right partitions
    sorted_left = quicksort(left);
    sorted_right = quicksort(right);
    
    % Concatenate the sorted partitions with the pivot value in between
    arr = [sorted_left, equal, sorted_right];
end
624 chars
24 lines

The quicksort function takes an input array arr and recursively sorts it using the Quick Sort algorithm. The base case is when the length of the array is one or zero, in which case the array is already sorted.

The algorithm chooses a pivot value from the array using a random index, partitions the array into three sub-arrays (elements less than the pivot, elements equal to the pivot, and elements greater than the pivot), and recursively sorts the left and right partitions. Finally, the sorted left and right partitions are concatenated with the pivot value in between to form the sorted array.

Note: This implementation chooses a random pivot value to avoid worst-case performance on already sorted arrays. However, this also means that the algorithm's runtime is not deterministic. If you need deterministic runtime, you can modify the code to choose a fixed pivot value (e.g. the median of the array).

gistlibby LogSnag