Sorting an array with if, for and while loop only.

I have an array A and I want array B as result using only if, for and while loops (no in-built function).
A = [0 1 2 3 4 5 0 6 7 8 0 9 10 11 0 12 13 ]
B= [ 0 1 2 3 4 5 0 -6 -7 -8 0 9 10 11 0 -12 -13]

3 件のコメント

Bjorn Gustavsson
Bjorn Gustavsson 2021 年 8 月 13 日
Look for the matlab on-ramp material to get you started on programming in matlab, look in your corse-book on the different sorting algorithms and start doodling with them, you can use playing-cards or just scribble the numbers on small pieces of paper. Then you'll quickly get up to speed on algorithms, programming, and matlab, if or when you run into problems that has to do with either the algorithms, the programming or how to implement them in matlab people will be helpful finding you solutions to that. If we on the other hand spoon-feed you with a solution you'll learn nothing. Welcome to matlab.
Rishabh Chaudhary
Rishabh Chaudhary 2021 年 8 月 13 日
Sure and thank you for your valuable words.
Jan
Jan 2021 年 9 月 7 日
The vector B is not sorted, especially not a sorted version of vector A.
Maybe B is a copy of A where the sign in changed whenever a 0 occurs. Before you can implement this in code, you have to define exactly, what you want to achieve.

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

回答 (1 件)

Sreedhar Arumugam
Sreedhar Arumugam 2021 年 9 月 7 日

0 投票

There are many sorting algorithms that can be used to answer your question.
As a starter, I would recommend learning Bubble Sort which works by repeatedly swapping adjacent elements if they are in the wrong order. You can read up on Bubble Sort and look at some sample cases here -
Once you understand the algorithm, the next step is implementing it in MATLAB.
arr = [5 4 3 2 1];
arr_size = length(arr);
for j = 0 : arr_size-1
for i = 1: arr_size-j-1
if arr(i)>arr(i+1)
temp = arr(i);
arr(i) = arr(i+1);
arr(i+1) = temp;
end
end
end

1 件のコメント

Jan
Jan 2021 年 9 月 7 日
Although this is a sorting, it does not produce the wanted output:
B= [ 0 1 2 3 4 5 0 -6 -7 -8 0 9 10 11 0 -12 -13]

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

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

製品

リリース

R2020a

質問済み:

2021 年 8 月 13 日

コメント済み:

Jan
2021 年 9 月 7 日

Community Treasure Hunt

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

Start Hunting!

Translated by