Effacer les filtres
Effacer les filtres

Selection Sort FUNCTION help in understanding it

9 vues (au cours des 30 derniers jours)
Nour Salhab
Nour Salhab le 12 Nov 2017
Commenté : Nour Salhab le 13 Nov 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!

Réponse acceptée

Roger Stafford
Roger Stafford le 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.
  1 commentaire
Nour Salhab
Nour Salhab le 13 Nov 2017
Thank you that was very clear!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Shifting and Sorting Matrices dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by