<?php
function quicksort($array)
{
  $length = count($array);

  if ($length <= 1) return $array;

  //get the middle of the array
  $pivot_key = $length%2 ? ($length+1)/2-1 : $length/2;
  $pivot  = $array[$pivot_key];

  //split array in two parts
  $left = $right = array();

  //left part will contain numbers that are < than the pivot point
  //right part will contain numbers that are >= pivot
  foreach($array as $k => $value)
  {
    if ($k == $pivot_key)
      continue;
    else if ($value < $pivot)
      $left[] = $value;
    else
      $right[] = $value;
  }

  //use recursion to sort the left and the right parts
  return array_merge(quicksort($left), array($pivot_key => $pivot), quicksort($right));
}
?>
Published in: PHP
Download

Related snippets