Php inserts a sorting method to implement array sorting instances and array instances. Php insert sorting method to implement array sorting. array example this article describes the php insert sorting method to implement array sorting. Share it with you for your reference. The specific analysis is as follows: php insert sorting method to implement array sorting instances and array instances
This example describes how to sort arrays by using the php insert sorting method. Share it with you for your reference. The specific analysis is as follows:
The basic idea of insert sorting method is as follows: we also use cases to explain whether to sort data in ascending order by $ arr = array.
Implementation principle: assume (not actually created) that there is an ordered array $ arr = array (2) and compare it with $ arr [1] = 6. if 6> 2, move $ arr [0] to $ arr [1], and insert 6 to $ arr [0. Next, compare $ arr [2] = 3 with $ arr [1] = 2, 3> 2, then $ arr [1] = 2 continues and moves to the $ arr [2] position. the original $ arr [3] = 3 is inserted to the $ arr [1] position, insert 9 to the combined position. The final result is (9, 6, 3, 2 ). It can also be sorted through the count ($ arr)-1 large loop.
Code rule analysis:
First large loop: $ [1] to $ [0;
The second big cycle: $ [2] to $ [1], $ [1] to $ [0;
The third cycle: $ [3] to $ [2], $ [2] to $ [1], $ [1] to $ [0;
PHP code, using function encapsulation for ease of use
<? 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 ); insertSort ($ myarr); echo"
";print_r($myarr);?>
Code implementation analysis:
The first big cycle:
$ I = 1 array (2, 6, 3, 9)
$ J = 1 run 6 and 2 ratio: $ arr [1] = 2; $ arr [0] = 6, get (6, 2, 3, 9)
The second cycle:
$ I = 2 array (6, 2, 3, 9)
$ J = 2: execute 3 and 2: convert to $ arr [2] = 2, $ arr [1] = 3, get (6, 3, 2, 9)
$ J --, $ j = 1 execution $ arr [1] and $ arr [0] ratio: condition not true
The third cycle:
$ I = 3 array (6, 3, 2, 9)
$ J = 3 run 9 and 2 ratio: convert to $ arr [3] = 2, $ arr [2] = 9, get (6, 3, 9, 2)
$ J --, $ j = 2 run 9 and 3 ratio: change to $ arr [2] = 3, $ arr [1] = 9, get (6, 9, 3, 2)
$ J --, $ j = 1. execute 9 and 6: convert to $ arr [1] = 5, $ arr [0] = 9, and get (9, 6, 3, 2)
I hope this article will help you with php programming.
Examples in this article describes how to sort arrays using the php insert sorting method. Share it with you for your reference. The specific analysis is as follows :...