Copy codeThe Code is as follows:
/**
* Quick sorting implemented by Recursive Method
* @ Param $ seq
* @ Return array
*/
Function quicksort ($ seq)
{
If (count ($ seq)> 1 ){
$ K = $ seq [0];
$ X = array ();
$ Y = array ();
$ _ Size = count ($ seq); // do not use count ($ seq) in loop.
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;
}
}
/** Implement with iteration
* @ Param $ seq
* @ Return array
*/
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;
}
// $ TestArr = array (5545, 5, 6, 7675,100, 9,233,566,789,456, 23, 55, 7, 4,343,564, 5, 45657, 8,998, 9, 34, 55, 6, 5, 6433, 67, 6, 6766, 4, 2, 42,256 34, 34343, 3, 3,454, 4, 65,667 8, 57,545 5 );
For ($ I = 0; $ I <20; $ I ++ ){
$ TestArr [] = mt_rand (0,10000 );
}
// Var_dump ($ testArr );
Echo count ($ testArr). '<br> ';
$ Start = microtime ();
Echo count (quicksort ($ testArr). '<br> ';
Echo microtime ()-$ start. '<br> ';
Var_dump (quicksort ($ testArr ));
Echo '------------------------------------------------------------------------ <br> ';
Echo count ($ testArr). '<br> ';
$ Start = microtime ();
Echo count (quicksortX ($ testArr). '<br> ';
Echo microtime ()-$ start. '<br> ';
Var_dump (quicksortX ($ testArr ));