PHP Associative array sorting (quick sort)
Cause
Well, I admit that lately I've been working with quick sort, a variety of test writing quick sort programs, now using PHP to achieve a quick sorting, unlike the previous article, this time the PHP fast line can solve the actual needs.
Use environment and Conditions
There is a case where the associative array inside PHP, if the following array data:
$array = Array (' name ' = ' Xiao ', ' age ' + 3), array (' name ' = ' Wang ', ' age ' = 1), array (' name ' = = ' Chen ', ' age ' = 2));
We want to sort the array for the Age field, and PHP's own functions, no matter what sort, obviously don't meet our needs, so we can write a quick sort code ourselves, and quickly implement our requirements.
Note the situation
There is no pointer in PHP, so when we want to refer to the pass, we can not just like C code, so write quicksort (int *a, int begin, int end), but to use the PHP & operator, the address of the array is passed with the fast sorting function, This makes it possible to implement reference passing in PHP instead of value passing.
Quick Sort Code
Quicksortprocess ($array, 0, Count ($array)-1);p Rint_r ($array);/** * Description: Get the location of the central point in quick sort */function quickpa Rtition (& $array, $left, $right) {//1. Benchmark Definition $stand = $array [$left];//2. Scan from both ends to the middle until $left = = $right And while ($left < ; $right) {while ($left < $right && $array [$right] ["Age"] >= $stand [' age ']) {$right--;} if ($left < $right) {$array [$left + +] = $array [$right];} while ($left < $right && $array [$left] ["Age"] <= $stand [' age ']) {$left + +;} if ($left < $right) {$array [$right--] = $array [$left];}} 3. Get the central point location $array [$left] = $stand; return $left;} /** * Description: Quick Sort main process function */function quicksortprocess (& $array, $begin, $end) {//1. Variable definition $pivot = NULL;//Central point if ($beg In < $end) {$pivot = Quickpartition ($array, $begin, $end); Quicksortprocess ($array, $begin, $pivot-1); Quicksortprocess ($array, $pivot + 1, $end);}}
I used this quick sort on the project, very happy, not in vain this October 1 vacation spent n days ac quick sort C code
-
1 floor dickeylth yesterday 14:30
-
This problem can be consulted in the next PHP usort, write a custom sort callback function on the line. See also: http://www.php.net/manual/zh/function.usort.php
-
Re: zinss26914 yesterday 15:27
-
reply DICKEYLTHN Check the link you gave, it is true, you can save a lot of code, reply, haha, actually also want to write in the actual project with their own sorting algorithm, always call PHP's own function, feel that they will not write the program