How does the bubble sort actually work?

5 ビュー (過去 30 日間)
Hussain Hayat
Hussain Hayat 2015 年 7 月 25 日
回答済み: Steven Lord 2015 年 7 月 30 日
So the bubble sort function. I cant quite figure it out. (attached picture). What is k and what is j. I get the general idea about how it continuously compares and substitutes two values. But Why do we declare sorted as 1 at the start of loop. And what is j and k exactly. Can someone walk me through this step by step? I cant seem to get the substitution part either. Please help. Oh and in the end why do we declare y=x;
  3 件のコメント
Hussain Hayat
Hussain Hayat 2015 年 7 月 30 日
Dont you know bubble sort? Its not that complicated you know
David Young
David Young 2015 年 7 月 30 日
編集済み: David Young 2015 年 7 月 30 日
As for other sorting algorithms, the most entertaining explanation is given by AlgoRythmics. They won't tell you what k and j are, but they genuinely help you understand the underlying algorithm. Note that their array indexing is zero-based (as in C) rather than one-based (as in MATLAB), but that shouldn't worry you too much.

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

回答 (1 件)

Steven Lord
Steven Lord 2015 年 7 月 30 日
You're right, bubble sort isn't that complicated. I like the name "sinking sort" mentioned as an alternative name in the Wikipedia page. At each step where you compare neighbors, the lighter/smaller neighbor "floats" towards the front of the vector (analogous to the surface of a body of water) and the heavier/larger neighbor "sinks" towards the bottom of the vector (the bottom of the lake/ocean/etc.) It may take multiple passes for heavy items on the top of the water to sink all the way to their correct position on the bottom, one position swap at a time.
Even though you didn't attach anything, my guess is that the variable named sorted indicates whether you're done. Note in the Wikipedia page that you can't tell if you're done unless you've gone through a whole pass with no swaps. So if you do any swaps in a pass, sorted becomes false and you can tell at the end whether you're done just by looking that that variable.

カテゴリ

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