Home >php教程 >PHP源码 >PHP implements quick sort algorithm

PHP implements quick sort algorithm

大家讲道理
大家讲道理Original
2016-11-08 17:30:341299browse

<?php
 
function quicksort($seq) {
 
  if (count($seq) > 1) {
 
    $k = $seq[0];
 
    $x = array();
 
    $y = array();
 
    for ($i=1; $i<count($seq); $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;
 
  }
 
}
 
  
 
$arr = array(12,2,16,30,8,28,4,10,20,6,18);
 
print_r(quicksort($arr));
 
?>

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn