Bubble sort not working like I want it

2 ビュー (過去 30 日間)
Benjamin
Benjamin 2013 年 2 月 11 日
x = rand([12,1])
for j = 1:numel(x)-1;
if x(j) > x(j+1);
temp1 = x(j);
x(j) = x(j+1);
x(j+1) = temp1;
end
end
The script seems to recognize when an element is larger than the next, but it doesn't flip the elements. I don't understand why :S

回答 (3 件)

Benjamin
Benjamin 2013 年 2 月 11 日
A while loop that reset the iteration in case of a swap worked wonders!
  1 件のコメント
Azzi Abdelmalek
Azzi Abdelmalek 2013 年 2 月 11 日
編集済み: Azzi Abdelmalek 2013 年 2 月 11 日
You are just puting the greatest value at the end of your array. You should repeat the operation from 1 to n-1 then from 1 to n-2 and so on

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


Honglei Chen
Honglei Chen 2013 年 2 月 11 日
This only gets the largest element to the bottom. You need another level of iteration to sort the rest of them.

Azzi Abdelmalek
Azzi Abdelmalek 2013 年 2 月 11 日
編集済み: Azzi Abdelmalek 2013 年 2 月 11 日
x=[8 10 2 4 6]
x(1)<x(2) % no action x(1)=8 , x(2)=10
x(2)>x(3) % x(2)=2; x(3)=10
at this step you have : 8,2,10, your array can't be sorted!

カテゴリ

Help Center および File ExchangeShifting and Sorting Matrices についてさらに検索

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by