Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

i would like to use an insertion sort method to alphabetically sort a matrix of

ID: 3812576 • Letter: I

Question

i would like to use an insertion sort method to alphabetically sort a matrix of string in Matlab.

For example;

I am thinking of approaching the code with a comparator function so that within a for loop it will compare the iterated string and sort the matrix. I have trouble figuring how to do so.

Explanation / Answer

An insertion sort method to alphabetically sort a matrix of string in Matlab: array = ['apple','cat','bee'] for i = 2:length(array) value = array(i); j = i - 1; array_j=array(1:j); array_j_indices=cumsum(array_j>value); [~,n]=find(array_j_indices==1); newArray=array; array(n+1:i)=array_j(array_j>value); j=j-max(array_j_indices); array(j+1) = value; end %forLoop disp(array); Explanation: First take elements from j to 1 in an array, since while loop will eventually scan through those elements. Find which of the elements are greater than the value and take its cumulative sum which will tell us how many elements are greater than the value. Because that is the amount we have to decrement j by. Now, find where the first 1 occurs (i.e. the first index at which the number is greater than value, since we have to shift every element to the right by 1 position from that index). After that, decrement j and put the value back.