Selection Sort FUNCTION help in understanding it
9 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Nour Salhab
il 12 Nov 2017
Commentato: Nour Salhab
il 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!
0 Commenti
Risposta accettata
Roger Stafford
il 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.
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Shifting and Sorting Matrices in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!