Python bubble sort

Source: Internet
Author: User

Bubble sort

As the name implies, the bubble sort intuitively means that the larger the bubble, the faster it will be, and the number that corresponds to the list is the largest one to select, then proceed sequentially.

For example myList = [1,4,5,0,6], the comparison is: the adjacent two numbers first to compare, that is mylist[0] and mylist[1], found not ">" relationship, continue to compare mylist[1] and mylist[2] ... In turn, found mylist[2] > mylist[3] (ie 5>0), the exchange, so go through the first full list comparison to get a new list [1,4,0,5,6], and then each scan to get a new list as follows:

First time: [1,4,0,5,6]

Second time: [1,0,4,5,6]

Third time: [0,1,4,5,6]

Fourth time: [1,4,5,0,6]

Example: data = [10,4,33,21,54,3,8,11,5,22,2,1,17,13,6] Bubble sort data

1. For loop

The first type: data = [10,4,33,21,54,3,8,11,5,22,2,1,17,13,6]count = 0for J in range (len data):          #外层循环15次 for    i in range ( Len (data)-1):    #内层循环14次        if data[i] > data[i+1]:            tmp = data[i+1]            data[i+1] = Data[i]            data[i] = tmp        count + = 1print (data) print ("Count:", Count) #result: [1, 2, 3, 4, 5, 6, 8, ten, one,,, six, four, 54]count:210, second: data = [10,4,33,21,54,3,8,11,5,22,2,1,17,13,6]count = 0for J in range (1,len (data)): For            I in range (len (data)-j):            if data[i] > data[i+1]:            tmp = data[i+1]            data[i+1] = Data[i]            data[i] = tmp        count + = 1print (dat A) print ("Count:", Count) #result: [1, 2, 3, 4, 5, 6, 8, ten, one,, 54]count:105

  

  

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.