And the efficiency is 3 times worse. Therefore, recursion in PHP must be treated with caution.
I recently wrote a quick sort algorithm and found that the recursive efficiency in PHP cannot be one size fits all, and may behave differently in various servers.
Copy code The code is as follows:
function qsort(&$arr)
{
_quick_sort($arr , 0, count($arr) - 1);
}
/**
* Quick sort using recursive algorithm.
*
* @param array $arr The array to sort
* @param int $low The lowest sorted subsection
* @param int $high The highest sorted field
*/
function _quick_sort(&$arr, $low, $high)
{
$low_data = $arr[$low];
$prev_low = $low;
$prev_high = $high;
while ($low < $high)
{
while ($arr[$high] >= $low_data && $low < $high) {
$high--;
}
if ($low < $high) {
$arr[$low] = $arr[$high];
$low++;
}
while ($arr[$low] <= $low_data && $low < $high) {
$low++;
}
if ($low < $high) {
$arr[$high] = $arr[$low];
$high--;
}
}
$arr[$low] = $low_data;
if ($prev_low < $low) {
_quick_sort($arr, $prev_low, $low);
}
if ($low + 1 < $prev_high) {
_quick_sort($arr, $low + 1, $prev_high);
}
}
function quick_sort(& $arr)
{
$stack = array();
array_push($stack, 0);
array_push($stack, count($arr) -1);
while ( !empty($stack)) {
$high = array_pop($stack);
$low = array_pop($stack);
$low_data = $arr[$low];
$prev_low = $low;
$prev_high = $high;
while ($low < $high)
{
while ($arr[$high] >= $low_data && $low < $high) {
$high--;
}
if ($low < $high) {
$arr[$low] = $arr[$high];
$ low++;
}
while ($arr[$low] <= $low_data && $low < $high) {
$low++;
}
if ($low < $high) {
$arr[$high] = $arr[$low];
$high--;
}
}
$arr[$low] = $low_data;
if ($prev_low < $low) {
array_push($stack, $prev_low);
array_push($stack, $low);
}
if ($low + 1 < $prev_high) {
array_push($stack, $low + 1);
array_push($stack, $prev_high);
}
}
}
The following is the code to test the speed:
Copy the code The code is as follows:
function qsort_test1()
{
$arr = range(1, 1000);
shuffle($arr);
$arr2 = $arr;
$t1 = microtime(true);
quick_sort($arr2) ;
$t2 = microtime(true) - $t1;
echo "Cost of non-recursive call:" . $t2 . "n";
$arr1 = $arr;
$t1 = microtime(true);
qsort($arr1);
$t2 = microtime(true) - $t1;
echo "Cost of recursive call:" . $t2 . "n";
}
On my IIS server (CGI) mode, my test results are:
Cost of non-recursive call: 0.036401009559631
Cost of recursive call: 0.053439617156982
In On my Apache server, my test results are:
Cost of non-recursive calls: 0.022789001464844
Cost of recursive calls: 0.014809131622314
The results are completely opposite, and the PHP version is the same.
It seems that the efficiency of recursion needs to be analyzed in detail.
http://www.bkjia.com/PHPjc/320823.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/320823.htmlTechArticleAnd the efficiency is 3 times worse. Therefore, recursion in PHP must be treated with caution. I recently wrote a quick sorting algorithm and found that the recursive efficiency in PHP cannot be one size fits all.