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 CenterFile Exchange에서 Shifting and Sorting Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by