Home >Backend Development >PHP Tutorial >PHP insertion sort method to implement array sorting example_PHP tutorial
This article mainly introduces the array sorting implemented by php insertion sort. The example analyzes the principle and specific implementation skills of insertion sort. , has certain reference value, friends in need can refer to it
The example in this article describes how to implement array sorting using PHP insertion sort. Share it with everyone for your reference. The specific analysis is as follows:
The basic idea of insertion sorting method: also use a case to illustrate, still use $arr = array(2,6,3,9), sort from large to small.
Implementation principle: Suppose (without actually creating) there is an ordered array $arr = array(2), use $arr[1]=6 to compare it with it, if 6>2, use $arr[ 0] is then moved to position $arr[1], and 6 is inserted into position $arr[0]. Then, $arr[2]=3 is compared with $arr[1]=2, 3>2, then $arr[1]=2 continues to move to the $arr[2] position, the original $arr[3]=3 Insert it into the $arr[1] position, and then continue to insert 9 into the closing position. The final result is (9,6,3,2). Sorting can also be achieved after count($arr)-1 large loops.
Code pattern analysis:
The first big loop: $[1] and $[0] ratio;
The second big cycle: $[2] versus $[1], $[1] versus $[0];
The third big cycle: $[3] versus $[2], $[2] versus $[1], $[1] versus $[0];
PHP code uses function encapsulation for ease of use
?
3 4 5 7
10
13 14 15
|
function insertSort(&$arr){
for($i=1;$i"; print_r($myarr); ?> |