Although in the development of Web applications such as PHP, we do not emphasize the importance of ordering, because PHP itself has brought such as sort () and so powerful sorting functions, but on some important occasions, such as some high concurrency, I think the impact of the sorting algorithm can not be ignored. So here we introduce recursive sorting and iterative sorting.
Recursive method :
/**
* Recursive method to achieve fast ordering
/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 ordering of iterative method
/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:
/**
* Generates a random array of * * for
($i =0; $i <5; $i + +) {
$testArr []=mt_rand (0,100);
}
Var_dump ($TESTARR);
Var_dump (Quicksort ($TESTARR));
Var_dump (Quicksortx ($TESTARR));