Objective
Interviews often have interviewers like to ask how to do bubble sort? This question is believed to be able to overwhelm a batch of heroes, this article will explain in detail how to use Python to bubble sort.
First, the basic principle
1. Concept:
Bubble sort (Bubble sort) is a simpler sort algorithm in the field of computers. It repeatedly visited the sequence to sort, comparing two elements at a time, and swapping them out if they were wrong in the order. The work of the sequence of visits is repeated until no more need to be exchanged, that is, the sequence is sorted. The name of the algorithm is because the larger the element will slowly "float" to the top of the sequence, hence the name. 2. Algorithm principle: The bubble sorting algorithm works as follows: (from backward) > compare adjacent elements.
If the first one is bigger than the second, swap them both.。 > does the same for each pair of adjacent elements, starting with the last pair from the first pair to the end. At this point, the last element should be the maximum number. > Repeat the above steps for all elements, except for the last one. > continues to repeat the above steps each time for fewer elements, until there are no pairs of numbers to compare.
Ii. exchange of two numbers
1. If a = ten, B = 20 How to exchange two number?
2. Implementing the two-digit switching principle is actually very simple, set a temporary variable C to:
> First pass the value of a to C, at which point the value of C is 10, and the value of a is 10.
> then pass the value of B to a, when the value of a is 20,b or 20
> finally pass the value of C to B, at which point the value of B is 10.
3.python inside Exchange two number not so complicated, this method is OK:
>a, B = B, a
Third, the traversal compares the adjacent number
1. For example a queue is: [1, 3, 10, 9, 21, 35, 4, 6]
2. You can do a traversal, compare adjacent numbers, the previous number is larger than the number of exchanges, so that the first traversal can sink the largest number to the last position
3. For ease of understanding, the place of exchange is circled in red.
Iv. cyclic sinking
1. The above traversal comparison only sinks once, sinking the largest number to the last position, then it is necessary to sink the second-largest number to the second-lowest position,
Loop in turn until the smallest number is at the top.
2. Here s is the length of the Li queue first, and then the range function is reversed and becomes: [7, 6, 5, 4, 3, 2, 1, 0]
V. Sort ()
1. True, Python is not so troublesome in ordering, a function is done: sort ()
Vi. Reference Code
# coding:utf-8li = [1, 3, 9,4, 6 = range (len (LI)) [:: -1]print s for in s: for in Range (i): if li[j] > Li[j + 1]: + 1] = li[j + 1], li[j]# sort function # Print Li
Python Note 2-bubble sort