Php selects the sorting method for array sorting instance analysis and array instance analysis. Php selects sorting method to implement array sorting instance analysis. array instance Analysis This article analyzes the php selects sorting method to implement array sorting. Share it with you for your reference. Specific Analysis: php selects sorting method to implement array sorting instance analysis and array instance analysis
In this article, we analyze how php selects a sorting method to sort arrays. Share it with you for your reference. The specific analysis is as follows:
The basic idea of selecting sorting method: Use cases to explain it directly. for example, there is an array $ arr = array (,), sorted from large to small.
The first large loop: it first assumes that $ arr [0] is the maximum value, and then corresponds to $ arr [1] ~ $ Arr [3] is compared. if it is large, it is exchanged. The process is as follows (,) --- 2 and 6 ratio --->) --- 6 and 3 ratio ---> (6, 2, 3, 9) --- 6 and 9 ratio ---> (9, 2, 3, 6 ). Note that the subscript here also needs to change.
The second large loop: assume that $ arr [1] is the largest (excluding $ arr [0]), respectively with $ arr [2] ~ For $ arr [3], the process is like this (9, 2, 3, 6) ---- 2 and 3 ratio ----> (9, 3, 2, 6) --- 3 and 6 ratio ---> (9, 6, 2, 3 ).
The third big loop: assume that $ arr [2] is the largest, compared with $ arr [3], the process is like this (9, 6, 2, 3) --- 2 and 3 ratio ---> (9, 6, 3, 2)
Similarly, after a large loop of N-1, you can sort it out
The PHP code is as follows. function encapsulation is also used here.
<?phpfunction selectSort(&$arr){ for($i=0;$i
";print_r($myarr);?>
Code analysis:
The first big cycle:
$ I = 0 array (2, 6, 3, 9)
$ J = 1, execute 2 and 6 ratio: to $ arr [0] = 6, $ arr [1] = 2, $ max = 6 (6, 2, 3, 9)
$ J = 2. compare 3 to 6: do not execute
$ J = 3: compare 9 to 6: change to $ arr [0] = 9, $ arr [3] = 6, $ max = 9 (9, 2, 3, 6)
The second cycle:
$ I = 1, $ max = $ arr [1] = 2, array (9, 2, 3, 6)
$ J = 2, execute 3 and 2 ratio: to $ arr [1] = 3, $ arr [2] = 2, $ max = 3 (9, 3, 2, 6)
$ J = 3. compare the values of 6 and 3: $ arr [1] = 6, $ arr [3] = 3, $ max = 6 (9, 6, 2, 3)
The third cycle:
$ I = 2, $ max = $ arr [2] = 2, array (9, 6, 2, 3)
$ J = 3, execute 3 and 2 ratio: to $ max [2] = 3, $ arr [3] = 2, $ max = 3 (9, 6, 3, 2)
I hope this article will help you with php programming.
In this article, we analyze how php selects the sorting method to sort arrays. Share it with you for your reference. Specific analysis...