Introduction to bubble sorting:
Bubble Sort is a simple sorting algorithm in the computer science field.
It repeatedly visits the series to be sorted, compares two elements at a time, and exchanges them if their order is wrong.
The work of visiting a sequence is repeated until there is no need for exchange, that is, the sequence has been sorted.
The name of this algorithm comes from because the smaller elements will slowly "float" to the top of the series through the exchange.
How the bubble sorting algorithm works:
Compares adjacent elements. If the first is bigger than the second, exchange the two of them.
Perform the same operation on each adjacent element, from the first to the last. At this point, the final element should be the largest number.
Repeat the preceding steps for all elements except the last one.
Continue to Repeat the above steps for fewer and fewer elements until there is no need to compare them.
PHP code example:
| The code is as follows: |
Copy code |
|
$ A = array ('3', '8', '1', '4', '11', '7 ');
Print_r ($ );
$ Len = count ($ );
// From small to large
For ($ I = 1; $ I <$ len; $ I ++)
{
For ($ j = $ len-1; $ j >=$ I; $ j --)
If ($ a [$ j] <$ a [$ j-1])
{// If it is from large to small, just change the judgment here to if ($ B [$ j]> $ B [$ j-1]).
$ X = $ a [$ j];
$ A [$ j] = $ a [$ j-1];
$ A [$ j-1] = $ x;
}
} |
Let's look at another one.
| The code is as follows: |
Copy code |
|
<? Php
# Bubble sorting
$ Arr = array (28,112, 20,434, 65,765, 33,553, 45,423 );
$ Tmp;
For ($ I = 0; $ I <count ($ arr)-1; $ I ++ ){
For ($ j = 0; $ j <count ($ arr)-1-$ I; $ j ++ ){
If ($ arr [$ j]> $ arr [$ j + 1]) {
$ Tmp = $ arr [$ j];
$ Arr [$ j] = $ arr [$ j + 1];
$ Arr [$ j + 1] = $ tmp;
}
}
}
Print_r ($ arr ); |