This article mainly introduces two examples of fast sorting algorithms in PHP. This article provides the implementation code, which are implemented by recursive method and iterative method, respectively, for more information, see. although we do not emphasize the importance of sorting in web application development such as PHP, PHP has already brought () such a powerful sorting function, but in some important scenarios, such as high concurrency, I think the impact of sorting algorithms can no longer be ignored. So here we will introduce recursive sorting and iterative sorting.
Recursion:
/*** Quick sorting implemented by recursive method */function quicksort ($ seq) {$ k = $ seq [0]; $ x = array (); $ y = array (); for ($ I = 1; $ I <$ _ size; $ I ++) {if ($ seq [$ I] <= $ k) {$ x [] = $ seq [$ I];} else {$ y [] = $ seq [$ I] ;}$ x = quicksort ($ x ); $ y = quicksort ($ y); return array_merge ($ x, array ($ k), $ y);} else {return $ seq ;}}
Iteration method:
/*** Fast sorting of iterative methods */function quicksortx (& $ seq) {$ stack = array ($ seq); $ sort = array (); while ($ stack) {$ arr = array_pop ($ stack); if (count ($ arr) <= 1) {if (count ($ arr) = 1) {$ sort [] = & $ arr [0];} continue;} $ k = $ arr [0]; $ x = array (); $ y = array (); $ _ size = count ($ arr); for ($ I = 1; $ I <$ _ size; $ I ++) {if ($ arr [$ I] <= $ k) {$ x [] = & $ arr [$ I];} else {$ y [] = & $ arr [$ I] ;}}! Empty ($ y) & array_push ($ stack, $ y); array_push ($ stack, array ($ arr [0]);! Empty ($ x) & array_push ($ stack, $ x);} return $ sort ;}
Usage:
/*** Generate a random array */for ($ I = 0; $ I <5; $ I ++) {$ testArr [] = mt_rand (0,100 );} var_dump ($ testArr); var_dump (quicksort ($ testArr); var_dump (quicksortx ($ testArr ));