image thumbnail

Insertion Sort MatLab Function

by

 

[output] is an array of number which is the sorted version of [input].

insertion_sort(unsorted)
function sorted = insertion_sort(unsorted)
    array_size = size(unsorted,2);
    for pivot = 2:array_size
        for j = 1:pivot-1
            if (unsorted(j)>unsorted(pivot))
                temp = unsorted(pivot);
                unsorted (j+1:pivot) = unsorted (j:pivot-1);
                unsorted(j) = temp;        
            end
        end
    end
    sorted = unsorted; 
end

Contact us