How does the bubble sort actually work?

7 views (last 30 days)
Hussain Hayat
Hussain Hayat on 25 Jul 2015
Answered: Steven Lord on 30 Jul 2015
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 Comments
Hussain Hayat
Hussain Hayat on 30 Jul 2015
Dont you know bubble sort? Its not that complicated you know
David Young
David Young on 30 Jul 2015
Edited: David Young on 30 Jul 2015
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.

Sign in to comment.

Answers (1)

Steven Lord
Steven Lord on 30 Jul 2015
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.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!