Classic sorting algorithm-bubble sort
The principle is to compare adjacent numbers in ascending order or in ascending order,
After such a trip, the largest or smallest number is switched to the last one,
Then compare and exchange data from the beginning until the last and second digits are over.
The example is sorted in ascending order,
Original array to be sorted| 6 | 2 | 4 | 1 | 5 | 9 |
First sort (External Loop)
For the first time, compare 6> 2 switches (inner loop)
Status before switch| 6 | 2 |4 | 1 | 5 | 9 |
Status After switch| 2 | 6 |4 | 1 | 5 | 9 |
The second comparison, 6> 4 exchanges
Status before switching | 2| 6 | 4 |1 | 5 | 9 |
Status After switch | 2| 4 | 6 |1 | 5 | 9 |
The third comparison, 6> 1 Exchange
Status before switching | 2 | 4| 6 | 1 |5 | 9 |
Status After switch | 2 | 4| 1 | 6 |5 | 9 |
Comparison of the fourth time, 6> 5 exchanges
Status before switching | 2 | 4 | 1| 6 | 5 |9 |
Status After switch | 2 | 4 | 1| 5 | 6 |9 |
For the fifth comparison, do not swap for 6 <9
Status before switching | 2 | 4 | 1 | 5| 6 | 9 |
Status After switch | 2 | 4 | 1 | 5| 6 | 9 |
Second sort (External Loop)
For the first time, the comparison is 2 <4 without exchange.
Status before switch| 2 | 4 |1 | 5 | 6 | 9 |
Status After switch| 2 | 4 |1 | 5 | 6 | 9 |
The second comparison, 4> 1 Exchange
Status before switching | 2| 4 | 1 |5 | 6 | 9 |
Status After switch | 2| 1 | 4 |5 | 6 | 9 |
Comparison of the third time in pairs, 4 <5 without exchange
Status before switching | 2 | 1| 4 | 5 |6 | 9 |
Status After switch | 2 | 1| 4 | 5 |6 | 9 |
For the fourth comparison, do not exchange 5 <6
Status before switching | 2 | 1 | 4| 5 | 6 |9 |
Status After switch | 2 | 1 | 4| 5 | 6 |9 |
Third sort (External Loop)
The first two-to-one comparison 2> 1 Exchange
Status After switch| 2 | 1 |4 | 5 | 6 | 9 |
Status After switch| 1 | 2 |4 | 5 | 6 | 9 |
For the second comparison, 2 <4 is not exchanged.
Status After switch | 1| 2 | 4 |5 | 6 | 9 |
Status After switch | 1| 2 | 4 |5 | 6 | 9 |
Comparison of the third time in pairs, 4 <5 without exchange
Status After switch | 1 | 2| 4 | 5 |6 | 9 |
Status After switch | 1 | 2| 4 | 5 |6 | 9 |
The fourth sorting (External Loop) has no exchange
The fifth sorting (External Loop) has no exchange
After sorting is completed, the final result is output 1 2 4 5 6 9.
Bubble sort animation demonstration
Back to main directory [classic Sorting Algorithm] [Collection]