Bubble Sort:
There is a set of numbers to be sorted, and we are here to sort the numbers in small to large order.
Compares the first number (40) to the second number (20), > 20, the swap position. The second number (40) compares to the third number (30), and >30, the swap position. The third number (40) is compared to the fourth number (10), and >10, the swap position. Compares the fourth number (40) to the fifth number (50), <50, and does not move. In this way, the top number is the largest number, and we just need to sort the next four numbers.
#!/usr/bin/env pythonimport randomdef bubble_sort(data): length = len(data) for i in range(len(data) - 1):#冒泡n-1次 for j in range(len(data)-i - 1):#比较次数n-i-1 if (data[j] > data[j + 1]):#从小到大 tmp = data[j] data[j] = data[j + 1] data[j + 1] = tmpr = random.Random()#定义空列表,并追加数值data = []for n in range(0, 10): data.append(r.randint(1, 20))print("初始为:")print(data)print("冒泡排序后:")bubble_sort(data)print(data)
Python bubble sort