Bubble Sorting Algorithm and bubble Algorithm
The demo array is:
$ A = array (,); // The subscript is ,.
Calculation process description:
Start from the left of the array and compare the size of two adjacent data in two pairs. If the left is larger than the right, they are exchanged. After "one trip", you can determine that the largest data is placed on the rightmost.
In this way, if you continue to take the next hop on the "remaining data", you must determine that the maximum value of the remaining data is placed on the rightmost of the remaining data.
Demo:
| Original array: |
9 |
3 |
5 |
8 |
2 |
7 |
| After the first trip: |
3 |
5 |
8 |
2 |
7 |
9 |
| After the second trip: |
3 |
5 |
2 |
7 |
8 |
9 |
| After the third round: |
3 |
2 |
5 |
7 |
8 |
9 |
| After the fourth round: |
2 |
3 |
5 |
7 |
8 |
9 |
| After the fifth tour: |
2 |
3 |
5 |
7 |
8 |
9 |
Rule Description:
1. Assume that n data entries exist in the array;
2. The number of workers to be compared is n-1;
3. The number of data to be compared for each trip is one less than that for the previous trip. The first trip needs to compare n (n N-1 1 times );
4. If there is no comparison, if the "data on the left" is greater than the "data on the right", the two are switched.
The code is demonstrated as follows:
<? Php $ a = array (,); // The subscript is, echo "Before sorting:"; print_r ($ ); $ n = count ($ a); // Number of for ($ I = 0; $ I <$ n-1; ++ $ I) // This is n-1 {for ($ k = 0; $ k <$ n-$ I-1; ++ $ k) // This is the number of comparisons {if ($ a [$ k]> $ a [$ k + 1]) {$ t = $ a [$ k]; $ a [$ k] = $ a [$ k + 1]; $ a [$ k + 1] = $ t ;}} echo "<br/> after sorting: "; print_r ($ );
Running result:
Before sorting: array ([0] => 9 [1] => 3 [2] => 5 [3] => 8 [4] => 2 [5] => 7)
After sorting: array ([0] => 2 [1] => 3 [2] => 5 [3] => 7 [4] => 8 [5] => 9)