Bubble Sorting in PHP

Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in wrong order (Accending or Descending).

Example:

First Pass:
( 5 1 4 2 8 ) –> ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps since 5 > 1.
( 1 5 4 2 8 ) –>  ( 1 4 5 2 8 ), Swap since 5 > 4
( 1 4 5 2 8 ) –>  ( 1 4 2 5 8 ), Swap since 5 > 2
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5), algorithm does not swap them.

Second Pass:
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 )
( 1 4 2 5 8 ) –> ( 1 2 4 5 8 ), Swap since 4 > 2
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –>  ( 1 2 4 5 8 )

Now, the array is already sorted, but our algorithm does not know if it is completed. The algorithm needs one whole pass without any swap to know it is sorted.

Third Pass:
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )

Implementation of this algorathim in PHP

$numbers=array(12,23,45,20,5,6,34,17,9,56);
$n=count($numbers);
for ($c = 0 ; $c < ( $n - 1 ); $c++)
{
 for ($d = 0 ; $d < ($n - $c - 1); $d++)
 {
   if ($numbers[$d] > $numbers[$d+1]) /* For decreasing order use < */
   {
  $swap = $numbers[$d];
  $numbers[$d]   = $numbers[$d+1];
  $numbers[$d+1] = $swap;
   }
 }
}

echo "Sorted list in ascending order <br />";
 
for ( $c = 0 ; $c < $n ; $c++ )
     echo $numbers[$c]." ";


Output : Output of the above code will be looking like this.

Sorted list in ascending order 
5 6 9 12 17 20 23 34 45 56


If you like this post don't forgot to leave a comment.

Chears 
Happy Coding :)

3 Comments

Previous Post Next Post