Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions algorithms/sorting/quick_sort.m
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
function sortedArray = quick_sort(array)

if numel(array) <= 1 %If the array has 1 element then it can't be sorted
sortedArray = array;
return
end

pivot = array(end);
array(end) = [];

%Create two new arrays which contain the elements that are less than or
%equal to the pivot called "less" and greater than the pivot called
%"greater"
less = array( array <= pivot );
greater = array( array > pivot );

%The sorted array is the concatenation of the sorted "less" array, the
%pivot and the sorted "greater" array in that order
sortedArray = [quick_sort(less) pivot quick_sort(greater)];

end