Python Bubble Sort

Source: Internet
Author: User

Bubble sort (Bubble sort) is a simple sort algorithm. It iterates over the sequence of columns to be sorted, compares two elements at a time, and if their order is wrong, change them in order.

The work of traversing the sequence is repeated until there is no more element to be exchanged, that is, the sequence is sorted. The algorithm is named because the smaller elements are exchanged and slowly "float" to the top of the sequence.

The bubbling Sort algorithm works as follows:

Compares the adjacent elements. If the first one is larger (ascending) than the second one, they are exchanged for both.

Compare each pair of adjacent elements to do the same work, starting with the first pair to the end. When this is done, the final element will be the maximum number.

Repeat the above steps for all elements, except for the last one.

Continue to repeat the above steps for the remaining elements until there are no pairs of numbers to compare.

We need to do a n-1 bubble process, each corresponding to the number of comparisons as shown:


defBubble_sort (alist): N=Len (alist) forJinchRange (n-1): forIinchRange (0,n-1): ifAlist[i] > Alist[i+1]: alist[i], Alist[i+1] = alist[i+1], Alist[i]if __name__=="__main__": Li= [54, 25, 17, 44, 88, 13, 55, 20, 33] PrintLi Bubble_sort (li)PrintLi

Complexity of Time

Optimal time complexity: O (n) (indicates that traversing a discovery does not have any elements that can be exchanged, the sort ends.) )

Worst time complexity: O (N*n)

Stability: Stable

Python 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.