How does the bubble sort actually work?

5 Ansichten (letzte 30 Tage)
Hussain Hayat
Hussain Hayat am 25 Jul. 2015
Beantwortet: Steven Lord am 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 Kommentare
Hussain Hayat
Hussain Hayat am 30 Jul. 2015
Dont you know bubble sort? Its not that complicated you know
David Young
David Young am 30 Jul. 2015
Bearbeitet: David Young am 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.

Melden Sie sich an, um zu kommentieren.

Antworten (1)

Steven Lord
Steven Lord am 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.

Kategorien

Mehr zu Shifting and Sorting Matrices finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by