Bubble Sort Algorithm in PHP

Posted by Tully on Thu 01 July 2010

Yesterday I posted an example of the Bubble Sort algorithm in C++.

Today I wrote the sorting algorithm in PHP.

Bubble Sort Algorithm in PHP

<?php
$numbers = array(1,3,2,5,2);
$array_size = count($numbers);

echo "Numbers before sort: ";
for ($i = 0; $i < $array_size; $i++)
echo $numbers[$i];
echo "\n";

for ($i = 0; $i < $array_size; $i++) {
    for ($j = 0; $j < $array_size; $j++) {
        if ($numbers[$i] < $numbers[$j]) {
            $temp = $numbers[$i];
            $numbers[$i] = $numbers[$j];
            $numbers[$j] = $temp;
        }
    }
}

echo "Numbers after sort: ";
for($i = 0; $i < $array_size; $i++)
    echo $numbers[$i];
    echo "\n";