Algorithm principle:
Compare the adjacent elements. If the first one is bigger than the second one, swap them both.
Do the same work for each pair of adjacent elements, from the first pair to the end of the last couple. At this point, the final element should be the largest number.
Repeat the above steps for all elements except the last one.
Continue to repeat the previous steps for less and fewer elements until no pair of digits need to be compared.
Realize
Suppose there is such an array: [4, 1, 3, 2]
Bubble sort to start with the first number, this number is compared to the following number, if the number is larger than the back, exchange their position.
For example, for the first time compare 4 and 1, find 4:1 Large, Exchange-> [1, 4, 3, 2]
The second comparison 4 and 3, found still 4 large, Exchange-> [1, 3, 4, 2]
The third time compares 4 and 2, still 4:2 large, Exchange-> [1, 3, 2, 4]
So after the first cycle, the maximum number of 4 is top to the end of the array, like bubbles from the bottom of the same. So, to complete the sequence of the entire array, just put the largest number to the end, and then the second round the second largest number to the second position, and then the third round .... All the way down the loop.
Back to just the array, the second round of comparison began, and now the state is [1, 3, 2, 4]
Compare 1 and 3,1 less than 3, skip-> [1, 3, 2, 4]
Compare 3 and 2,3 greater than 2, Exchange-> [1, 2, 3, 4]
This will stop here, because the first round has the top 4 to the end, so the second round is just to make sure that the second largest number is the second to the bottom of the line.
Then proceed to the third round (though at present it appears that the sort has been completed)
Compare 1 and 2 without swapping [1, 2, 3, 4]
This comparison is complete. The principle is very simple.
def bubble_sort (list)
list.each_index do |index|
(List.length-index-1). Times do |e|
If list[e] > list[e + 1]
list[e], list[e + 1] = list[e + 1], list[e]
end