>>> for I in range (Len (a)-1):
... for j in Range (Len (a)-i-1):
... if a[j]>a[j+1]:
... a[j],a[j+1]=a[j+1],a[j]
...
The time complexity of bubble sorting is the idea of O (n^2) bubble sort: compare two adjacent elements each time, and swap them if they're in the wrong order.
For example, there are five numbers: 12, 35, 99, 18, 76, from the big to the small sort, compare the adjacent two bits
- First trip:
- First time comparisons: 35, 12, 99, 18, 76
- Second comparisons: 35, 99, 12, 18, 76
- Third comparisons: 35, 99, 18, 12, 76
- Fourth time comparisons: 35, 99, 18, 76, 12
After the first comparison, the smallest of the five numbers is already on the last side, then only the first four numbers are compared, and so on.
- Second trip
99, 35, 76, 18, 12
- Third Trip
99, 76, 35, 18, 12
- Four trips
99, 76, 35, 18, 12
Compare complete
Bubble sorting principle: Each trip can only be a number of digits, if there are N number to sort, just the number of n-1, that is, to do n-1 operation (the number has been returned without comparison)
#!/usr/bin/env python# Coding:utf-8Def Bubblesort(nums):For IInchRangeLen (nums)-1):# This loop is responsible for setting the number of bubbles sortedfor J in range ( len (nums) -i-1): # J for list subscript if nums[j] > nums[j+1]: nums[j], Nums[j+1] = nums[j< Span class= "DV" >+1], Nums[j] return numsnums = [5,2,45,6, 8,2,1]print Bubblesort (nums)
Cons: Bubble sorting solves the problem of wasted space in bucket sequencing, but the efficiency of bubble sorting is particularly low
python-Bubble Sort