gistlib
Here is an implementation of quicksort algorithm in MATLAB:
main.mfunction 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 chars26 lines
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
To use the function, call it with the input array as argument:
main.minput_array = [5 8 1 3 9 6]; sorted_array = quicksort(input_array); disp(sorted_array); 88 chars4 lines
input_array = [5 8 1 3 9 6]; sorted_array = quicksort(input_array); disp(sorted_array);
Output:
main.m1 3 5 6 8 9 32 chars2 lines
1 3 5 6 8 9
gistlibby LogSnag