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-8defBubblesort (nums): forIinchRange (len (nums)-1):#This loop is responsible for setting the number of times the bubble sort is performed forJinchRange (len (nums)-i-1):#J for List subscript ifNUMS[J] > Nums[j+1]: nums[j], nums[j+1] = nums[j+1], Nums[j]returnnumsnums= [5,2,45,6,8,2,1]PrintBubblesort (Nums)
Cons: Bubble sorting solves the problem of wasted space in bucket sequencing, but the efficiency of bubble sorting is particularly low
From: http://www.cnblogs.com/qlshine/p/6017957.html
Bubble sort of thinking python bubble sort