Clear Filters
Clear Filters

Selection Sort FUNCTION help in understanding it

9 views (last 30 days)
This is the code I got as a solution to an exercise, I'm trying to read it but there's a part I don't understand (I'm still new)
clc %clear command window
clear; %clear all variables in workspace
A = input('Enter numbers between [ ] separated by comma, i.e. [1,2,3,4]: ');
n = length(A);
for i=1:n-1
[x index] = min(A(i:n));
minIndex = index + i-1;
temp = A(i);
A(i) = A(minIndex);
A(minIndex) = temp;
end;
disp(A);
What does this part do exactly (put into words):
[x index] = min(A(i:n));
minIndex = index + i-1;
temp = A(i);
A(i) = A(minIndex);
A(minIndex) = temp;
thank you!

Accepted Answer

Roger Stafford
Roger Stafford on 12 Nov 2017
(Corrected) Starting with i = 1 and ending with n-1, the first line finds the index of the minimum element in A from i to n, and the second line corrects that index by adding i-1 so that it is the correct index with respect to the entire A vector. The next three lines picks up the i-th element of A into ‘temp’, and does a swap between the i-th element of A and the minimum that was just found. The net result at the end is that A is now sorted in ascending order.

More Answers (0)

Categories

Find more on Shifting and Sorting Matrices in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!