Saturday 6 July 2013

How to sort an array elements using Bubble Sort in php?

Answer
<?php
function BubbleSort($numarray)
{
$max = count($numarray);
for ($i = 1; $i < $max;$i++)
{
for ($j = 0; $j < $max - $i; $j++)
{

if ($numarray[$j] > $numarray[$j + 1])
{
$temp = $numarray[$j];
$numarray[$j] = $numarray[$j + 1];
$numarray[$j + 1] = $temp;
}
}
}
return $numarray;

}

$array1 = array( 10, 20, 20, 40, 30,25, 30, 35, 40, 45, 50, 55);

$bubblesort = BubbleSort($array1);

echo "Sorted array using BubbleSort <br>";
for($i=0;$i<count($bubblesort );$i++)
{
echo $bubblesort [$i]." , ";
}
?>

No comments:

Post a Comment