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 件のコメント

per isakson
per isakson 2012 年 9 月 19 日
Google for "bubble sort"
Aviroop Dutt Mazumder
Aviroop Dutt Mazumder 2012 年 9 月 21 日
Thanks per, it worked! Do i need to do the same for descending numbers? Cheers

サインインしてコメントする。

回答 (2 件)

Honglei Chen
Honglei Chen 2012 年 9 月 19 日

1 投票

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 件のコメント

Aviroop Dutt Mazumder
Aviroop Dutt Mazumder 2012 年 9 月 21 日
Thanks Honglei, I used the bubble command to get the number output in an ascending order

サインインしてコメントする。

Jan
Jan 2012 年 9 月 22 日

0 投票

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 件のコメント

Safwan
Safwan 2016 年 11 月 22 日
Can you please explain to me why did you put
A(index) = -Inf;
Image Analyst
Image Analyst 2016 年 11 月 22 日
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!
James Tursa
James Tursa 2016 年 11 月 22 日
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.
Larissa Monjaraz
Larissa Monjaraz 2021 年 3 月 7 日
How would the code change if you wanted it in descending order?
Walter Roberson
Walter Roberson 2021 年 3 月 7 日
use min and +inf
Larissa Monjaraz
Larissa Monjaraz 2021 年 3 月 7 日
Ooooh that makes sense. Thank you!

サインインしてコメントする。

カテゴリ

ヘルプ センター および File ExchangeResizing 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