Wednesday, May 30, 2012

Sorting numbers using bubble sort technique in php ( Sorting Code)

 

Bubble sort

A bubble sort, a sorting algorithm that continuously steps through a list, swapping items until they appear in the correct order.
Bubble sort is a simple sorting algorithm. The algorithm starts at the beginning of the data set. It compares the first two elements, and if the first is greater than the second, it swaps them. It continues doing this for each pair of adjacent elements to the end of the data set. It then starts again with the first two elements, repeating until no swaps have occurred on the last pass. This algorithm's average and worst case performance is O(n2), so it is rarely used to sort large, unordered, data sets. Bubble sort can be used to sort a small number of items (where its inefficiency is not a high penalty). Bubble sort may also be efficiently used on a list that is already sorted except for a very small number of elements. For example, if only one element is not in order, bubble sort will take only 2n time. If two elements are not in order, bubble sort will take only at most 3n time...
<?php
$num=array(1,9,3,7,8,2,5,6);
function sorter($num)
{
    for ($i=0;$i<=count($num)-1;$i++)
{
    if($num[$i]>$num[$i+1])
    {
        //echo $num[$i].':'.$num[$i+1].'<br>';
        $temp=$num[$i];
        $num[$i]=$num[$i+1];
        $num[$i+1]=$temp;
        $num=sorter($num);
    }
   
    }
    return $num;
}
var_dump($num);
var_dump(sorter($num));
   
?>

No comments:

Post a Comment