To sort a given list by using Python for the bubbling algorithm
One of the things to note is the position of the swap value, the position swap cannot be directly assigned by the index, you need to introduce a temporary variable to complete
The example is to sort in ascending order, and if you need to sort in descending order, replace the ' > ' with the ' < '
Li = [33,2,10,1,123,123,557,5,3422,13123,88]print (LI) #先打印一下需要排序的列表for J in Range (1,len (LI)): #控制循环次数 For I in range (Len (LI)-1): #每次循环, sort if li[i] > li[i + 1]: #按列表中的索引对相邻的两个数字进行比较 temp = li[i] # Assign a large value to a temporary variable temp li[i] = li[i + 1] #通过引入一个临时变量的方法, the position of the swap value li[i + 1] = Tempprint (li) #打印最后的排序结果
Execution Result:
[33, 2, 10, 1, 123, 123, 557, 5, 3422, 13123, 88] [1, 2, 5, 10, 33, 88, 123, 123, 557, 3422, 13123]
Python bubbling Algorithm