Selection Sort FUNCTION help in understanding it
9 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Roger Stafford
2017-11-12
(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.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Shifting and Sorting Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!