The bubble sort idea is actually:
The size of the previous and subsequent numbers is continuously compared, and if the previous number is greater than the next number, the position of the two number is exchanged. The goal is to achieve a sort from small to large.
The first cycle, the smallest number bubbles to the position of the first number;
If we want to compare, we must first try to get these two numbers.
That's two marks.
A Mark I mark the previous number, a Mark J marks the number after this I, and then the comparison can be.
The code is as follows:
1Data_set = [9,1,22,31,45,3,6,2,11]2 3 forIinchRange (len (data_set)-1): # i from 0 to Countdown first4 forJinchRange (i+1, Len (data_set)): #j from I+1 to the last5 ifData_set[i] >Data_set[j]:6DATA_SET[I],DATA_SET[J] =Data_set[j],data_set[i] #交换位置7 8 Print(Data_set)
Results:
[1, 2, 3, 6, 9, 11, 22, 31, 45]
Python bubble sort