0 Why write this article
On the one hand, the classical sorting algorithm 冒泡排序 is reviewed, on the other hand, through practical application to test the knowledge of Python basic knowledge, including range function, Len function, for loop, if statement, function definition and invocation, list sorting and other points. In practice to deepen understanding, to achieve the purpose of learning, to promote the study of the long-run.
1 What is bubble sort
The basic idea of bubble sorting is to think of the elements that need to be sorted as "bubbles", the smallest "bubbles" that emerge the most quickly, and in front of them. The smaller "bubbles" are ranked in the second position, and so on. The bubbling sort requires several loops of the sequence, such as the I element in the sequence. First cycle, check the series from the bottom up, comparing the two adjacent elements. If the smaller element is below the sequence, and the smaller element is in front, then the largest element is placed at the bottom, then the second cycle does not need to compare the last element. And so on, the nth cycle only needs to start from the first element, compare i-n times, after i-1 the processing, the sequence is completed.
The use of bubble sorting is still minimal after learning more about sorting algorithms and in real-world usage scenarios. It is suitable for small data size, and its efficiency is relatively low, but as a sort of entry algorithm, it is worth learning.
2 Code Implementation
1 #Bubble Sort2 defBubble_sort (Numbers):3Numbers_len =len (Numbers)4 #can be added here to determine whether the list is empty5 forIinchRange (numbers_len-1, 0, 1):6 forJinchRange (i):7 ifNUMBERS[J] > Numbers[j+1]:8NUMBERS[J], numbers[j+1] = numbers[j+1], Numbers[j]9 Print(Numbers)Ten One defMain (): Anumbers = [23, 12, 9, 15, 6] - Bubble_sort (Numbers) - the if __name__=="__main__": - Main () - - #Core Code Analysis: + #Line 3rd: Get the length of the list you want to sort - #line 5th: Each cycle represents a single trip, the variable i is the number of times each trip needs to be compared + #Line 6th: Loop Comparison of adjacent two elements A #Line 7th: Determine the size of adjacent two elements at #Line 8th: Arrange the smaller numbers to the front
3 Running Results
4 built-in sorting functions
The detailed usage plan for sort and sorted is also written in another article.
Python version bubble sorting algorithm