In this paper, an example is given to analyze the method of selecting sorting by PHP. Share to everyone for your reference. The specific analysis is as follows:
The basic idea of choosing a sort method: direct use case to explain, for instance have an array $arr = Array (2,6,3,9), from big to small sort.
The first large cycle: it first assumes that $arr[0] is the maximum, and then compares it to $arr[1]~ $arr [3], if it is larger, then swaps, the process is this (2,6,3,9)---2 and 6---> (6,2,3,9)---6 and 3 than--- > (6,2,3,9)---6 and 9 ratio---> (9,2,3,6). Note that the subscript will also change here.
Second large cycle: assuming $arr[1] maximum (excluding $arr[0]), compared with $arr[2]~ $arr [3], the process is this (9,2,3,6)----2 and 3 ratio----> (9,3,2,6)---3 and 6---> ( 9,6,2,3).
The third big cycle: assuming $arr[2] is the largest, compared to $arr[3, the process is this (9,6,2,3)---2 and 3 ratio---> (9,6,3,2)
The same, after the N-1 of the large cycle, you can arrange out
The PHP code is as follows, which is also encapsulated with functions
<?php
function Selectsort (& $arr) {for
($i =0; $i <count ($arr); $i + +) {
$max = $arr [$i];
for ($j = $i +1; $j <count ($arr); $j + +) {
if ($max < $arr [$j]) {
$max = $arr [$j];
$arr [$j] = $arr [$i];
$arr [$i] = $max;
}
}} return $arr;
}
$myarr = Array (2,6,3,9);
Selectsort ($myarr);
echo "<pre>";
Print_r ($myarr);
? >
Code Analysis:
The first big cycle:
$i =0 Array (2,6,3,9)
$j = 1, perform 2 and 6 ratios: Become $arr[0]=6, $arr [1]=2, $max =6 namely (6,2,3,9)
$j = 2, performing 3 and 6 ratios: not executing
$j = 3, perform 9 and 6 ratios: Become $arr[0]=9, $arr [3]=6, $max =9 namely (9,2,3,6)
Second big cycle:
$i =1, $max = $arr [1]=2, Array (9,2,3,6)
$j = 2, perform 3 and 2 ratios: Become $arr[1]=3, $arr [2]=2, $max =3 namely (9,3,2,6)
$j = 3, perform 6 and 3 ratios: Become $arr[1]=6, $arr [3]=3, $max =6 namely (9,6,2,3)
The third big cycle:
$i =2, $max = $arr [2]=2, Array (9,6,2,3)
$j = 3, perform 3 and 2 ratios: Become $max[2]=3, $arr [3]=2, $max =3 namely (9,6,3,2)
I hope this article will help you with your PHP program design.