This article illustrates the method of implementing array ordering by PHP insertion sort. Share to everyone for your reference. The specific analysis is as follows:
The basic idea of inserting a sort method: the same case to explain, or to $arr = Array (2,6,3,9), from large to small sort.
Implementation principle: Suppose (not actually created) there is an ordered array $arr = Array (2), which is compared with $arr[1]=6, if 6>2, by moving $arr[0 back to the $arr[1 position, and 6 to the $arr[0 position. Then, $arr [2]=3 compared to $arr[1]=2, 3>2, then $arr[1]=2 continue to move to the $arr[2] position, the original $arr[3]=3 inserted into the $arr[1] position, and then continue to insert 9 into the closed position, the resulting result is (9,6,3,2). The same is done by Count ($arr)-1-time large loops, which can be sorted.
Code Law Analysis:
The first big cycle: $[1] and $[0] ratio;
Second big cycle: $[2] and $[1] ratio, $[1] and $[0] ratio;
The third big cycle: $[3] and $[2] ratio, $[2] and $[1] ratio, $[1] and $[0] ratio;
PHP code, using a function encapsulation to facilitate the use of the
<?php
function Insertsort (& $arr) {
for ($i =1; $i <count ($arr); $i + +) {
//$insertVal is the number
to be inserted for ($j = $i; $j >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 "<pre>";
Print_r ($myarr);
? >
Code Implementation Analysis:
The first big cycle:
$i =1 Array (2,6,3,9)
$j = 1 Perform 6 and 2 ratio: $arr [1]=2; $arr [0]=6, Get (6,2,3,9)
Second big cycle:
$i =2 Array (6,2,3,9)
$j = 2 Perform 3 and 2 ratio: become $arr[2]=2, $arr [1]=3, Get (6,3,2,9)
$j--, $j = 1 performing $arr[1] and $arr[0] ratios: conditions not established
The third big cycle:
$i =3 Array (6,3,2,9)
$j = 3 Perform 9 and 2 ratio: become $arr[3]=2, $arr [2]=9, Get (6,3,9,2)
$j--, $j = 2 Perform 9 and 3 ratio: become $arr[2]=3, $arr [1]=9, Get (6,9,3,2)
$j--, $j = 1 Perform 9 and 6 ratio: become $arr[1]=5, $arr [0]=9, Get (9,6,3,2)
I hope this article will help you with your PHP program design.