Selection Sort FUNCTION help in understanding it
9 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Nour Salhab
el 12 de Nov. de 2017
Comentada: Nour Salhab
el 13 de Nov. de 2017
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!
0 comentarios
Respuesta aceptada
Roger Stafford
el 12 de Nov. de 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.
Más respuestas (0)
Ver también
Categorías
Más información sobre Shifting and Sorting Matrices en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!