Python bubble sort note the main points are detailed

Source: Internet
Author: User
This article introduces the Python bubble sorting knowledge, involving the main details of bubble sort, this article through the example code to explain to you, the introduction of very detailed, with reference value, interested friends to see together

">

Bubble sort note three points:

1. The first layer cycle can be used without looping through all elements.

2. The two-layer loop variable is associated with the first-level loop variable.

3. The second loop must eventually loop through all the elements in the collection.

Example code one:

1. The first layer loops only n-1 elements.

2. When the first layer of the loop variable is n-1, the second layer loops all elements.

s = [3, 4, 1, 6, 2, 9, 7, 0, 8, 5]
# Bubble_sort
For I in range (0, Len (s)-1):
For j in range (i + 1, 0,-1):
If S[J] < S[j-1]:
S[J], s[j-1] = s[j-1], s[j]
For M in range (0, Len (s)):
Print (S[m])

Example code two:

1. The first layer loops all elements.

2. The second layer also loops through all the elements.

s = [3, 4, 1, 6, 2, 9, 7, 0, 8, 5]
For I in range (0, Len (s)):
For j in range (I, 0,-1):
If S[J] < S[j-1]:
S[J], s[j-1] = s[j-1], s[j]
For M in range (0, Len (s)):
Print (S[m])

The above is a small series to introduce the Python bubble sorting algorithm attention points, I hope that we have some help, if you have any questions please give me a message, small series will promptly reply to you.

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.