PHP insertion sorting Implements array sort instance, array instance
In this paper, we describe the method of inserting sorting in PHP to realize array sorting. Share to everyone for your reference. The specific analysis is as follows:
The basic idea of inserting the sorting method is to illustrate the same case, or to $arr = Array (2,6,3,9), from the large to the small sort.
Implementation principle: Suppose (not actually created) there is an ordered array $arr = Array (2), with $arr[1]=6 to compare it, if 6>2, by moving $arr[0] back to the $arr[1] position, and 6 inserted into the $arr[0] position. Then, $arr [2]=3 and $arr[1]=2, 3>2, then $arr[1]=2 continue to move to $arr[2] position, the original $arr[3]=3 inserted into the $arr[1] position, and then continue to insert 9 into the close position, the result is (9,6,3,2). It is also possible to sort by count ($arr)-1 cycles.
Code Law Analysis:
The first big cycle: $[1] and $[0] than;
The second big cycle: $[2] and $[1] than, $[1] and $[0] than;
The third big cycle: $[3] and $[2] than, $[2] and $[1] than, $[1] and $[0] than;
PHP code, using the function encapsulation, to facilitate the use of
<?phpfunction insertsort (& $arr) {for ($i =1; $i
0; $j-) {if ($arr [$j]> $arr [$j-1]) {$insertVal = $arr [$j]; $arr [$j] = $arr [$j-1]; $arr [$j-1] = $insertVal; }}}} $myarr = Array (2,6,3,9); Insertsort ($myarr); echo "
";p Rint_r ($myarr);? >
Code Implementation Analysis:
First big cycle:
$i =1 Array (2,6,3,9)
$j = 1 Perform 6 and 2 ratios: $arr [1]=2; $arr [0]=6, Get (6,2,3,9)
Second big cycle:
$i =2 Array (6,2,3,9)
$j = 2 performs 3 and 2 ratios: becomes $arr[2]=2, $arr [1]=3, gets (6,3,2,9)
$j--, $j = 1 Execute $arr[1] and $arr[0] ratio: condition not established
The third big cycle:
$i =3 Array (6,3,2,9)
$j = 3 performs 9 and 2 ratios: becomes $arr[3]=2, $arr [2]=9, gets (6,3,9,2)
$j--, $j = 2 Perform 9 and 3 ratios: Become $arr[2]=3, $arr [1]=9, Get (6,9,3,2)
$j--, $j = 1 Perform 9 and 6 ratios: Become $arr[1]=5, $arr [0]=9, Get (9,6,3,2)
I hope this article is helpful to everyone's PHP programming.
http://www.bkjia.com/PHPjc/959116.html www.bkjia.com true http://www.bkjia.com/PHPjc/959116.html techarticle The php Insertion Sort method realizes the array sort instance, the array instance describes the method which the PHP inserts the sorting method realizes the array sorting. Share to everyone for your reference. The specific analysis is as follows: ...