Bubble Sort Algorithm for Python

0 Why write this article

On the one hand, the classic sorting algorithm 冒泡排序is reviewed, and on the other hand, the basic knowledge of python is tested through practical application, including the range function, len function, for loop, if statement, function definition and call, list sorting and other knowledge points. Deepen understanding in practice, and achieve the purpose of applying what you have learned, using it to promote learning, and learning with each other.

1 What is bubble sort

The basic idea of ​​bubble sorting is to regard the elements to be sorted as "bubbles", and the smallest "bubble" surfaced the fastest and ranked first. Smaller "bubbles" come second, and so on. Bubble sort requires looping over the list several times, i.e. there are i elements in the list. In the first loop, the sequence is checked from the bottom up, and two adjacent elements are compared. If the smaller element is at the bottom of the sequence, put the smaller element at the front, and after comparing in turn, put the largest element at the bottom, and the second loop does not need to compare the last element. By analogy, the nth loop only needs to start from the first element, compare in times, and after i-1 times of processing, the sequence is sorted.

After learning more sorting algorithms in depth and in practical use cases, the use of bubble sort is still minimal. It is suitable when the data size is small, and its efficiency is relatively low, but as an entry-level sorting algorithm, it is still worth learning.

2 code implementation

1  #Bubble sort 
2  def bubble_sort(numbers):
 3      numbers_len = len(numbers)
 4      #You can add here to judge whether the list is empty 
5      for i in range(numbers_len-1, 0, -1 ):
 6          for j in range(i):
 7              if numbers[j] > numbers[j+1 ]:
 8                  numbers[j], numbers[j+1] = numbers[j+1 ], numbers[j]
 9              print (numbers)
 10  
11  def main():
 12      numbers = [23, 12, 9, 15, 6 ]
 13     bubble_sort(numbers)
 14  
15  if  __name__ == " __main__ " :
 16      main()
 17  
18  #Core code analysis: 
19  #Line 3: Get the length of the list to be sorted 
20  #Line 5: Each loop means one trip Sorting, the variable i is the number of times to be compared in each pass 
21  #Line 6: Loop to compare two adjacent elements 
22  #Line 7: Determine the size of two adjacent elements 
23  #Line 8: Put the number with the smaller value row to the front

3 Running results

4 Built-in sorting functions


The detailed usage plan of sort and sorted is written in another article.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325339395&siteId=291194637