Simple implementation of the Bubble Sorting Algorithm and Ruby version, and the Bubble Sorting Algorithm ruby
Algorithm principle:
Compares adjacent elements. If the first is bigger than the second, exchange the two of them.
Perform the same operation on each adjacent element, from the first to the last. At this point, the final element should be the largest number.
Repeat the preceding steps for all elements except the last one.
Continue to repeat the above steps for fewer and fewer elements until there is no need to compare them.
Implementation
Suppose there is an array like this: [4, 1, 3, 2]
The Bubble Sorting starts from the first number. We can compare this number with the subsequent number. If this number is larger than the subsequent number, we will switch their positions.
For example, when we compare 4 and 1 for the first time, we find that 4 is bigger than 1 and the switch is> [1, 4, 3, 2].
The second comparison is 4 and 3, and the result is still 4. Switch-> [1, 3, 4, 2]
The third comparison is 4 and 2, and still 4 is bigger than 2, switching-> [1, 3, 2, 4]
In this way, after the first round of loop, the maximum number of 4 is pushed to the end of the array, just like a bubble rising from the bottom of the water. Then, to complete the sorting of the entire array, you only need to top the maximum number to the end, and then the second round to the second to the last, and then the third round .... Keep repeating.
Return to the array. The comparison starts in the second round. The current status is [1, 3, 2, 4].
Compare 1 and 3, 1 less than 3, skip-> [1, 3, 2, 4]
Compare 3 and 2 with 2, switch-> [1, 2, 3, 4]
This round can be stopped here, because the first round has reached the top 4 of the maximum, so the second round only needs to ensure that the second number is at the bottom of the second.
Then proceed to the third round (although it seems that the sorting has been completed)
Compare the values of 1 and 2. You do not need to exchange [1, 2, 3, 4].
The comparison is complete here. 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 end endend