Python bubble sort

Source: Internet
Author: User

The bubble sort idea is actually:

The size of the previous and subsequent numbers is continuously compared, and if the previous number is greater than the next number, the position of the two number is exchanged. The goal is to achieve a sort from small to large.

The first cycle, the smallest number bubbles to the position of the first number;

If we want to compare, we must first try to get these two numbers.

That's two marks.

A Mark I mark the previous number, a Mark J marks the number after this I, and then the comparison can be.

The code is as follows:

  

1Data_set = [9,1,22,31,45,3,6,2,11]2 3  forIinchRange (len (data_set)-1): # i from 0 to Countdown first4      forJinchRange (i+1, Len (data_set)): #j from I+1 to the last5         ifData_set[i] >Data_set[j]:6DATA_SET[I],DATA_SET[J] =Data_set[j],data_set[i] #交换位置7 8 Print(Data_set)

Results:
[1, 2, 3, 6, 9, 11, 22, 31, 45]

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.