foreword
During interviews, interviewers often like to ask how to perform bubble sort? This question is believed to be stumbling to a group of heroes. This article will explain in detail how to use python to perform bubble sorting.
1. Basic Principles
1. Concept:
2. Swap two numbers
1. If a = 10, b = 20, how to exchange two numbers?
2. The principle of realizing the exchange of two numbers is actually very simple, just set a temporary variable c:
> Pass the value of a to c first, then the value of c is 10, and the value of a is still 10
> Then pass the value of b to a, at this time the value of a is 20, and the value of b is still 20
> Finally pass the value of c to b, at this time the value of b is 10
3. It is not so complicated to exchange two numbers in python, just use this method:
>a , b = b, a
3. Traverse and compare adjacent numbers
1. For example, a queue is: [1, 3, 10, 9, 21, 35, 4, 6]
2. You can do a traversal, compare the adjacent numbers, and exchange if the previous number is larger than the latter number, so that the first traversal can sink the largest number to the last position
3. For ease of understanding, the exchanged places are circled in red
4. Cyclic sinking
1. The above traversal comparison has only done one sinking, and the largest number is sinking to the last position, then the second largest number needs to sink to the penultimate position,
Loop through until the smallest number is on top.
2. Here s is to first calculate the length of the li queue, and then reverse the range function to become: [7, 6, 5, 4, 3, 2, 1, 0]
Five, sort () sorting
1. To tell the truth, sorting in python doesn’t have to be so troublesome, a function can do it: sort()
6. Reference code
# coding:utf-8 li = [1, 3, 10, 9, 21, 35, 4, 6] s = range (len (li)) [:: - 1 ] print s for i in s: for j in range(i): if li[j] > li[j + 1]: li[j], li[j + 1] = li[j + 1 ], li[j] #sort function # li.sort () print li