Return to Snippet

Revision: 30899
at August 25, 2010 02:40 by Sverri


Initial Code
/*
  sortIntegers()
  ---
  Uses the "bubble sort" algorithm to sort an array of
  integers. PHP's sorting functions are fine, so this
  function is merely to demonstrate how it could be done.
*/

function sortIntegers($x)
{
  $count = count($x)-1;
  
  for ($i=0; $i<$count; $i++)
  {
    if ($x[$i]<$x[$i+1]) continue;
    
    list($x[$i],$x[$i+1]) = array($x[$i+1],$x[$i]);
    
    $x = sortIntegers($x);
  }
  return $x;
}

// Example

$integers = array(6,3,2,8,9,4,0,1,7,5);

$sorted = sortIntegers($integers);

echo '<pre>', implode(',',$sorted), '</pre>';

Initial URL


Initial Description


Initial Title
Bubble sort integers

Initial Tags


Initial Language
PHP