python-bubbling Algorithm (Bubble Sort)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.