I have decided to learn to program in MATLAB (r2013a) so I can use Matlab to study
various fields of mathematics but mostly so I can study algorithm design and analyses in general.
Since I have plenty of generic programming experience (C++, MySQL, python) I though I would go straight to
implementing a simple algorithm, "Insertion Sort" as described in "Introduction to Algorithms 3rd ed"; and it isn't going well.
I have reviewed the syntax of the operators and structural satements but I just don't see the issue.
The function should take an array and sort it obviously, but instead it takes the second element in the array and writes it to each subsequent element in the array. On debug with breakpoints execution never seems to enter the while loop, I don't understand why the conditions are never met.
function [ sortedSet ] = insertionSort( targetSet ) for outerIndex = 2:length(targetSet) workingKey = targetSet(outerIndex); innerIndex = outerIndex - 1; while innerIndex > 0 && targetSet(innerIndex) >= workingKey targetSet(innerIndex + 1) = targetSet(innerIndex); innerIndex = innerIndex - 1; end targetSet(outerIndex + 1) = workingKey; end sortedSet = targetSet; end
>> A A = 14 11 9 13 13 14 13 19 5 15 >> B = insertionSort(A) B = 14 14 14 14 14 14 14 14 14 14 11 >>
Thanks for reading,