One: The bubbling algorithm, also called bubble sort, features the following:
1. Compare adjacent elements. If the first one is bigger than the second one, swap them both.
2. Do the same work for each pair of adjacent elements, starting from the first pair to the end of the last pair. At this point, the last element should be the maximum number.
3. Repeat the above steps for all elements except the last one.
4. Repeat the above steps each time for fewer elements until there are no pairs of numbers to compare.
Use Python's bubbling sort to complete the sorting of a set of unordered queues:
data = [10,4,33,21,54,3,8,11,5,22,2,2,2,1,17,13,6]Print(Data,"Original Queue") forJinchRange (1,len (data)-2):#cycle, the total length of the list queue is reduced by 2, because the following comparisons are two subscript bits backwards based on the subscript of the element forIinchRange (len (data)-j):#The number of times a small loop is subtracted from the number of times that cycle has been cycled, because cycle will have one of the largest elements on the far right once per loop, and the secondary element will not need to be looped. ifData[i] > Data[i+1]:#false into the first element is greater than the second elementTMP = data[i+1]#The first step is to save the second element to a temporary variableDATA[I+1] = Data[i]#The second step puts the value of the second element equal to the value of the previous larger elementData[i] = tmp#The third step is to place the previous element equal to the temporary variable of the smaller element behind it, thus completing the position substitutionPrint(Data,"the queue after bubbling sort") Execution Result: [10, 4, 33, 21, 54, 3, 8, 11, 5, 22, 2, 2, 2, 1, 17, 13, 6] Original queue [1, 2, 2, 2, 3, 4, 5, 6, 8, 10, 11, 13, 17, 21, 22, 33, 54] bubble sorted queue
Python Fifth: Bubbling algorithm, System standard module