Posted By

Sverri on 08/25/10


Tagged

integersbubblesort


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

seloh77


Bubble sort integers


 / Published in: PHP
 

  1. /*
  2.   sortIntegers()
  3.   ---
  4.   Uses the "bubble sort" algorithm to sort an array of
  5.   integers. PHP's sorting functions are fine, so this
  6.   function is merely to demonstrate how it could be done.
  7. */
  8.  
  9. function sortIntegers($x)
  10. {
  11. $count = count($x)-1;
  12.  
  13. for ($i=0; $i<$count; $i++)
  14. {
  15. if ($x[$i]<$x[$i+1]) continue;
  16.  
  17. list($x[$i],$x[$i+1]) = array($x[$i+1],$x[$i]);
  18.  
  19. $x = sortIntegers($x);
  20. }
  21. return $x;
  22. }
  23.  
  24. // Example
  25.  
  26. $integers = array(6,3,2,8,9,4,0,1,7,5);
  27.  
  28. $sorted = sortIntegers($integers);
  29.  
  30. echo '<pre>', implode(',',$sorted), '</pre>';

Report this snippet  

You need to login to post a comment.