note 11831 deleted from language.functions by felipe

[email protected]
Newsgroups php.notes
Message-ID <[email protected]>
Note Submitter: yasuo_ohgaki at hotmail dot com 

----

PHP supports recursion. I thought it worth to mention.

Simple Quick Sort using recursion works perfectly.

== OUTPUT ==
Recursion TEST

Array
(
    [0] => 12
    [1] => 23
    [2] => 35
    [3] => 45
    [4] => 56
    [5] => 67
)
== END OUTPUT ==

== QUICK SORT CODE ==
<?php

echo('<br>Recursion TEST<br>');

function swap(&$v, $i, $j) {
 $temp = $v[$i];
 $v[$i] = $v[$j];
 $v[$j] = $temp;
}

// Quick Sort integer array - $int_array[$left] .. $int_array[$right]
function qsort(&$int_array, $left, $right) {
 if ($left >= $right)
  return; // Do nothing if there are less than 2 array elements
 swap ($int_array, $left, intval(($left+$right)/2));
 $last = $left;
 for ($i = $left + 1; $i <= $right; $i++)
  if ($int_array[$i] < $int_array[$left])
   swap($int_array, ++$last, $i);
 swap($int_array, $left, $last);
 qsort($int_array, $left, $last-1);
 qsort($int_array, $last+1, $right);
}

$val = array(56,23,45,67,12,35);

qsort($val, 0, count($val)-1);

echo '<pre>';
print_r ($val);
echo '</pre>';

?>
== END QUICK SORT ==
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.