The bubbling sorting algorithm works as follows:
- Compares the adjacent elements. If the first one is bigger than the second one, swap them both.
- Do the same for each pair of adjacent elements, starting with the last pair from the first pair to the end. At this point, the last element should be the maximum number.
- Repeat the above steps for all elements, except for the last one.
- Repeat the above steps each time for fewer elements, until there are no pairs of numbers to compare.
In a nutshell: Adjacent elements are compared, big in the back
Bubble sorting principle: Each trip can only be a number of digits, if there are N number to sort, just n-1 the number of digits,
That is to do n-1 (the number that has been returned does not have to be compared, because it is already the largest).
# coding:utf-8 nums = [ 12 , 99 , 18 , 76 , Span class= "DV" >2 ]count = len (nums) for I in range (0 , Count -1 ): # this cycle is responsible for setting the number of times the bubbling sort is performed for J in range (0 , Count- I -1 ): if nums[j] > nums[j+1 ]: nums[j], Nums[j+1 ] = nums[j+1
], Nums[j] # interchange print (nums)
Operation Result:
[12, 18, 76, 2, 99]
[12, 18, 2, 76, 99]
[12, 2, 18, 76, 99]
[2, 12, 18, 76, 99]
python-bubbling Algorithm (Bubble Sort)