0

Bubble Sorting

Would someone be able to explain the logic of the bubble sorting? I’ve looked at a few codes demonstrating it but do not yet understand it. My main question derives from the condition in the for loop that does the swapping. Why is it i<the size of the scans MINUS ONE? The minus one is what I do not understand. Wouldn’t you traverse though all of the iterations to swap?? If you do not understand my question, I have the exact area where the confusion is marked in the following code: (The output looks this way because I’m currently coding it replit.com/) https://code.sololearn.com/c1YVZZsdQr7q/?ref=app **UPDATE** For anyone interested, this resource helps clarify things greatly https://stackoverflow.com/questions/12259622/why-bubble-sort-needs-nested-loops/12259766#12259766

5th Apr 2021, 6:36 PM
Alejandro
2 odpowiedzi
+ 2
its minus one because if you notice, there are two for loops. in theory, one for loop focuses on one value, while the other checks it against all other values. if it didnt subtract one, you'd get a value that isnt in the arrays memory if you have a hard time imagining it, then dont. make a small example on a paper just write out the indexes and values that are being compared each round of the loop. Or use an ide to single step through the program and set up variable watches
5th Apr 2021, 6:41 PM
Slick
Slick - avatar
+ 1
So just to solidify: First loop- the minus one is due to the last number already being solved, not including this would result in an unnecessary iteration. Second- it would go out of the bounds of the array without.
5th Apr 2021, 8:45 PM
Alejandro