python-- bubble sort

The so-called bubble, is to be between any two elements, who would later move large until the largest element pushed to the bottom, then a trip to recycling, from the beginning pairwise comparison, but the trip has been discharged that would not be good elements compared.

Bubble sort of thought: it compares two adjacent elements, if they put them in the wrong order exchange position.

Bubble Sort principle: Only one number per trip homing, if there are n number of sort, simply return the number of bits n-1, n-1 that is to be operating times (already homing number do not have to compare).

Cons: Bubble Sort solve the problem of bucket sort waste of space, but the bubble sort is particularly low efficiency

python bubble sort code to achieve

 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 
 4 li = [33, 4, 15, 1, 456, 75, 45, 30, 20, 78, 99, 100, 67, 23, 10, 7]
 5 print("排序前:", li)
 6 for j in range(1, len(li)):
 7     for i in range(len(li) - j):
 8         if li[i] > li[i + 1]:
 9             temp = li[i]
10             li[i] = li[i + 1]
11             li[i + 1] =the TEMP
 12  Print ( " sorted: " , li)
View Code

 

Guess you like

Origin www.cnblogs.com/june-L/p/11605402.html