Select sort,
The demo array is:
$ A = array (,); // The subscript is ,.
Calculation process description:
Obtain the subscript of the maximum value of an array, and exchange the unit with the last unit. Then, obtain the maximum value from the remaining data and exchange the unit with the last unit, and so on, until there is only one data left, you don't need to find it.
Demo:
| Raw data: |
9 |
3 |
5 |
8 |
2 |
7 |
| After the first trip: |
7 |
3 |
5 |
8 |
2 |
9 |
| After the second trip: |
7 |
3 |
5 |
2 |
8 |
9 |
| After the third lie: |
2 |
3 |
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 records" for finding and exchanging the maximum unit is n-1;
3. Each trip requires the maximum number of units in "residual data", and the number of remaining data is 1 less in each trip. The first trip has n;
4. After finding the maximum unit, you must exchange the maximum unit with the last unit in the remaining array.
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 {// find the maximum unit $ max = $ a [0] at the beginning of each trip; // obtain the value of the first item $ pos = 0 for finding the maximum value; // obtain the subscript of the maximum value and the subscript of the first item for ($ k = 0; $ k <$ n-$ I; ++ $ k) {if ($ a [$ k]> $ max) {$ max = $ a [$ k]; $ pos = $ k ;}/// you can obtain the maximum value and its subscript first: the maximum unit // and then begin to exchange $ t = $ a [$ pos]; $ a [$ pos] = $ a [$ n-$ I-1]; $ a [$ n-$ I-1] = $ t;} echo "<br/> after sorting: "; print_r ($ );
The execution result is:
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)