PHP Two examples of fast sorting algorithms
This article mainly introduces two kinds of PHP fast sorting algorithm examples, this article directly give implementation code, using recursive method, iterative method to achieve, the need for friends can refer to the next
Although in Web application development such as PHP, we do not emphasize the importance of sorting too much, because PHP itself has taken such a powerful sort function as sort (), but in some important occasions, such as some high concurrency, I think the effect of sorting algorithm can not be ignored. So here we introduce recursive sorting and iterative sorting.
Recursive method:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21st 22 |
/** * Recursive method for fast sorting */ 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; } } |
Iterative method:
?
1 2 3 4 5 6 7 8 9 13 /p> + + / / / + + + + 25 + + $ + + + |
/** * Fast sequencing 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; } |
Use:
?
1 2 3 4 5 6 7 8 9 10 |
/** * 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)); |
http://www.bkjia.com/PHPjc/958570.html www.bkjia.com true http://www.bkjia.com/PHPjc/958570.html techarticle PHP Two examples of fast sorting algorithms This article mainly introduces the PHP two fast sorting algorithm examples, this article directly gives the implementation code, respectively, using recursive method, iterative method to achieve, the need of friends can ...