Arrange (array of 9 numbers) in ascending order. (no sort)

Please suggest me to find a commnad using for loop to Arrange (array of 9 numbers) in ascending order without using sort command. I used the following one, which didn't work
A = [4 16 36 64 1 9 25 49 81] B = [] for i = 1:9
B(i) = max(A)
find max(A)== 0
end

댓글 수: 2

Google for "bubble sort"
Thanks per, it worked! Do i need to do the same for descending numbers? Cheers

댓글을 달려면 로그인하십시오.

답변 (2개)

Honglei Chen
Honglei Chen 2012년 9월 19일
You can do
B = unique(A)
But seriously, are you trying to implement a sort algorithm in MATLAB? If so, there are many algorithms available, e.g., quick sort

댓글 수: 1

Thanks Honglei, I used the bubble command to get the number output in an ascending order

댓글을 달려면 로그인하십시오.

Jan
Jan 2012년 9월 22일
Improvement of your method:
A = [4 16 36 64 1 9 25 49 81];
B = zeros(1, 9); % Pre-allocate!
for ii = 1:9
[value, index] = max(A);
B(ii) = value;
A(index) = -Inf;
end
For 9 elements an insert-sort would be fine also.

댓글 수: 6

Can you please explain to me why did you put
A(index) = -Inf;
So that element of A will no longer be found as the maximum value of A in subsequent iterations. If you didn't do this, it would simply find the very same value of A each iteration!
This is to eliminate that particular element from the result of the next max(A) calculation, since that element has already been placed into the B vector.
How would the code change if you wanted it in descending order?
use min and +inf
Ooooh that makes sense. Thank you!

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Resizing and Reshaping Matrices에 대해 자세히 알아보기

질문:

2012년 9월 19일

댓글:

2021년 3월 7일

Community Treasure Hunt

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

Start Hunting!

Translated by