Can someone help me understand bubble sort.
28 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Hussain Hayat
il 2 Ago 2015
Commentato: Katlyn Rivera
il 17 Feb 2022
I cant understand bubble sort(the code is given above). How is j and k used. In the for loop why is [ j = 1 : n-k ]. What does fewer tests on each pass mean. And I cant understand how temp is used to switch two numbers in x. And why is sorter reset to 0 after each for loop. Can someone explain this part by part? I only get the basic idea of how two numbers are compared and then replaced (or not) but how is it checked. Which two numbers are chosen first?
Risposta accettata
Geoff Hayes
il 2 Ago 2015
Hussain - given the condition
x(j) > x(j+1)
the list is being sorted in ascending order (since the subsequent code replaces the j+1 element with the j element). Since k is initialized to zero, then when we enter the while loop, k is incremented by one (and so is set to one) and we then iterate over j from 1 to n-k or the length of the list less one as
k = k + 1;
for j = 1:n-k
So if the list is of size 10, j iterates from one to nine. We then compare the two neighbouring elements as
if x(j) > x(j+1)
trying to determine if the element at position j is greater than the element at position j+1. If this is true, and since we are sorting the list in ascending order, then we need to swap these two elements which we do with
temp = x(j);
x(j) = x(j+1);
x(j+1) = temp;
The idea is that we want to "push" the largest elements to the end of the list. We then set the sorted flag to zero and move on to the second iteration of the for loop. Note that we continue in this manner until we have iterated over each element and have pushed the largest element (of the list) to the end. If sorted is zero, then we repeat and increment k by one which means it is now 2. Since j iterates from 1:n-k then with k being two we iterate from one to eight (and so the comment fewer tests on each pass makes sense.
In order to better understand what the code is doing you should try it with a simple example and step through the code, line by line, to see how the list is being manipulated on each iteration. See http://blogs.mathworks.com/videos/2012/07/03/debugging-in-matlab/ for details on how to debug.
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Shifting and Sorting Matrices in Help Center e File Exchange
Prodotti
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!