Python Syntax: python-Bubble sorting and python syntax

Source: Internet
Author: User

Python Syntax: python-Bubble sorting and python syntax

After that, I said that I needed to collect data on the beauty human body art station. I used python to collect and learn python syntax knowledge. Now I want to share the python Bubble Sorting statements.

Bubble Sort is a simple sorting algorithm. It repeatedly traverses the series to be sorted, compares two elements at a time, and exchanges them if their order is wrong. The traversal of a Series repeats until there is no need to exchange, that is, the series has been sorted. The name of this algorithm comes from because the smaller elements will slowly "float" to the top of the series through the exchange.

The Bubble Sorting Algorithm operates as follows:

  • Compares adjacent elements. If the first one is larger than the second one (ascending), the two of them will be exchanged.

  • Perform the same operation on each adjacent element, from the first to the last. After this step is completed, the final element will 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.

Code implementation:


1
2
3
4
5
6
7
8
9
10
def bubble_sort(alist):     for in range(len(alist)-1,0,-1):         # J indicates the number of times to be compared for each traversal, which is gradually reduced         for in range(j):             if alist[i] > alist[i+1]:                 alist[i], alist[i+1= alist[i+1], alist[i]li = [54,26,93,17,77,31,44,55,20] bubble_sort(li)print(li)

 

Time Complexity

    • Optimal Time Complexity: O (n) (indicates that no elements can be exchanged during traversal, And the sorting ends .)

    • Worst time complexity: O (n2)

    • Stability: Stability

Related Article

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.