Say you were given a list of 6 numbers and you wanted to sort them from least to greatest. The list looks like this:
1 4 5 2 3 6
With Bubble Sort, you start from the beginning (the left in this case), and you put a "bubble" around the first two indices and sort, like so:
[1 4] 5 2 3 6
Since 1 < 4 (which is what we want), you move the "bubble" one index to the right.
1 [4 5] 2 3 6
...and so on and so forth...
1 4 [5 2] 3 6
At this point, 5 > 2, so those two would be swapped
1 4 [2 5] 3 6 1 4 2 [5 3] 6; 5 > 3 so we swap. 1 4 2 [3 5] 6 1 4 2 3 [5 6]
Then we start over at the beginning, and repeat until no further swaps are needed, i.e., until the list is sorted from least to greatest.
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Say you were given a list of 6 numbers and you wanted to sort them from least to greatest. The list looks like this:
1 4 5 2 3 6
With Bubble Sort, you start from the beginning (the left in this case), and you put a "bubble" around the first two indices and sort, like so:
[1 4] 5 2 3 6
Since 1 < 4 (which is what we want), you move the "bubble" one index to the right.
1 [4 5] 2 3 6
...and so on and so forth...
1 4 [5 2] 3 6
At this point, 5 > 2, so those two would be swapped
1 4 [2 5] 3 6
1 4 2 [5 3] 6; 5 > 3 so we swap.
1 4 2 [3 5] 6
1 4 2 3 [5 6]
Then we start over at the beginning, and repeat until no further swaps are needed, i.e., until the list is sorted from least to greatest.