Classic Sort algorithm-bubble sort bubble sort
The principle is that the adjacent number 22 is compared, in order from small to large or from large to small to exchange,
After such a trip, the largest or smallest number was exchanged to the last,
And then start from the beginning to the 22 comparison exchange, until the end of the second-to-last, the rest looks like examples
Examples for small to large sort,
Original array to sort | 6 | 2 | 4 | 1 | 5 | 9 |
First trip sort (outer loop)
First 22 comparison 6 > 2 swap (inner loop)
Pre-swap status | 6 | 2 | 4 | 1 | 5 | 9 |
Post-swap status | 2 | 6 | 4 | 1 | 5 | 9 |
Second 22 comparison, 6 > 4 swap
Pre-swap Status | 2 | 6 | 4 | 1 | 5 | 9 |
Post-swap Status | 2 | 4 | 6 | 1 | 5 | 9 |
Third 22 comparison, 6 > 1 swap
Pre-swap Status | 2 | 4 | 6 | 1 | 5 | 9 |
Post-swap Status | 2 | 4 | 1 | 6 | 5 | 9 |
Fourth time 22 comparison, 6 > 5 swap
Pre-swap Status | 2 | 4 | 1 | 6 | 5 | 9 |
Post-swap Status | 2 | 4 | 1 | 5 | 6 | 9 |
Fifth time 22 comparison, 6 < 9 no swap
Pre-swap Status | 2 | 4 | 1 | 5 | 6 | 9 |
Post-swap Status | 2 | 4 | 1 | 5 | 6 | 9 |
Second trip sort (outer loop)
First 22 comparison 2 < 4 no swap
Pre-swap status | 2 | 4 | 1 | 5 | 6 | 9 |
Post-swap status | 2 | 4 | 1 | 5 | 6 | 9 |
Second 22 comparison, 4 > 1 swap
Pre-swap Status | 2 | 4 | 1 | 5 | 6 | 9 |
Post-swap Status | 2 | 1 | 4 | 5 | 6 | 9 |
Third 22 Comparisons, 4 < 5 non-exchangeable
Pre-swap Status | 2 | 1 | 4 | 5 | 6 | 9 |
Post-swap Status | 2 | 1 | 4 | 5 | 6 | 9 |
Fourth time 22 comparison, 5 < 6 no swap
Pre-swap Status | 2 | 1 | 4 | 5 | 6 | 9 |
Post-swap Status | 2 | 1 | 4 | 5 | 6 | 9 |
Third trip sort (outer loop)
First time 22 comparison 2 > 1 swap
Post-swap status | 2 | 1 | 4 | 5 | 6 | 9 |
Post-swap status | 1 | 2 | 4 | 5 | 6 | 9 |
Second 22 comparison, 2 < 4 non-exchangeable
Post-swap Status | 1 | 2 | 4 | 5 | 6 | 9 |
Post-swap Status | 1 | 2 | 4 | 5 | 6 | 9 |
Third 22 Comparisons, 4 < 5 non-exchangeable
Post-swap Status | 1 | 2 | 4 | 5 | 6 | 9 |
Post-swap Status | 1 | 2 | 4 | 5 | 6 | 9 |
Four-trip sort (outer loop) No swap
Five-trip sort (outer loop) No swap
Paste the code that you wrote:
function Bubble_sort ($arr =array (1,43,54,62,21,66,32,78,36,76,39)) { $len = count ($arr); The layer loop controls the number of rounds that need to bubble for ($i =1; $i < $len; $i + +) {//This layer loop is used to control the number of times a number needs to be compared per round for ($k =0; $k < $len-$i; $k + +) { if ($arr [$k] > $arr [$k +1]) { $tmp = $arr [$k +1]; $arr [$k +1] = $arr [$k]; $arr [$k] = $tmp; @ $arr [' cly_times '] +=1; Set Loop End } if ($arr [' cly_times '] = = $arr [' cly_times ']-1) { return $arr; } } return $arr;}
The above describes the classic sorting algorithm-bubble sort bubble sort, including the aspects of the content, I hope to be interested in PHP tutorial friends helpful.