"Python Learning notes-data structures and algorithms" bubble sorting Bubble sort

Source: Internet
Author: User

Recommend a Visual Web site "Visual Algo": Url= ' https://visualgo.net/en/sorting '

This website gives the principles and processes of various sorting algorithms, which are visualized through dynamic forms. The related pseudo-code are also given, as well as the specific steps to execute to code.

"Bubble Sort"

You need to repeatedly visit the sequence of columns that need to be sorted. The size of the adjacent two items is compared during the visit, and if the order is not correct, two items are exchanged. Therefore, the maximum value of the part that needs to be sorted is moved to the appropriate location for each visit (pass).

This process looks like every item bubbles to the final position, and thus becomes a bubbling sort.

This gives the process of completing a visit, and finally the maximum value of this list is 93 moved to the far right of the list.

"Implementation of a bubble sort"

  

You can view the specific execution process through print N and K.

  

"Performance Analysis"

In the above implementation, regardless of what type of list is entered, the time complexity is O (N2), because the number of times to compare is (n-1) + (n-2) +...+1; Space complexity is O (1).

However, by recording where the swap is not required, the best-case performance can be reduced to O (n), as follows:

  

  

Of course, we can use the Python built-in function "sort ()" to achieve sorting, for example:

  

"Python Learning notes-data structures and algorithms" bubble sorting Bubble sort

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.