14

I need to do a bubble sort algorithm in PHP.

I want to know whether any one has any good examples that I can use, or an open source library which can do this.

I have a few spaces in a set (array), i want to fill these spaces with object (a person), so no space can have a male and a female, this why i am trying to find out a bubble sort algorithm.

My plan is to fill in any of the available spaces regardless of the gender, and after that sort them separately.

Thanks.

Lucas
  • 16,930
  • 31
  • 110
  • 182
nivanka
  • 1,352
  • 6
  • 23
  • 36
  • See my blog post with simple bubble sort implementation: http://blog.richardknop.com/2012/06/bubble-sort-algorithm-php-implementation/ – Richard Knop Jun 19 '12 at 10:19

7 Answers7

28
function bubble_sort($arr) {
    $size = count($arr)-1;
    for ($i=0; $i<$size; $i++) {
        for ($j=0; $j<$size-$i; $j++) {
            $k = $j+1;
            if ($arr[$k] < $arr[$j]) {
                // Swap elements at indices: $j, $k
                list($arr[$j], $arr[$k]) = array($arr[$k], $arr[$j]);
            }
        }
    }
    return $arr;
}

For example:

$arr = array(1,3,2,8,5,7,4,0);

print("Before sorting");
print_r($arr);

$arr = bubble_sort($arr);
print("After sorting by using bubble sort");
print_r($arr);
spongebob
  • 8,370
  • 15
  • 50
  • 83
Jayyrus
  • 12,961
  • 41
  • 132
  • 214
  • 1
    the best sorting algor is quick sort. with O(nlog(n)), is the faster algor to sort. you can see it here: http://www.phptutorialonline.com/php-quicksort.aspx – Jayyrus Jan 25 '12 at 12:22
  • 1
    your loops dont stop when there is no swap. you should use while or break the loop – user2997418 Dec 05 '16 at 15:50
  • @蒋艾伦 it will be even faster if he uses a `foreach` loop. – FluorescentGreen5 May 02 '17 at 03:06
  • @JackTurky you can not just say one sort is the best of them all. It all depends on size of data set, complexity of data and few other things. Decisions should be made with testing on specific data sets to determine the best tool for the job ;) For example, insertion sort is much faster than quicksort on small sample size, let's say array with 10 random unique values between 0 and 100. – Matic Krajnc Feb 14 '19 at 18:44
25

Using bubble sort is a very bad idea. It has complexity of O(n^2).

You should use php usort, which is actually a merge sort implementation and guaranteed O(n*log(n)) complexity.

A sample code from the PHP Manual -

function cmp( $a, $b ) { 
  if(  $a->weight ==  $b->weight ){ return 0 ; } 
  return ($a->weight < $b->weight) ? -1 : 1;
} 

usort($unsortedObjectArray,'cmp');
Rifat
  • 7,628
  • 4
  • 32
  • 46
  • but my need is not only to sort, i need to assign those objects (people) to the spaces – nivanka Jan 25 '12 at 11:11
  • Yeah! you can do that too. BTW, I think you didn't get my solution properly. – Rifat Jan 25 '12 at 11:14
  • if( $a->weight == $b->weight ){ return 0 ; } return ($a->weight < $b->weight) ? -1 : 1; --- this is the important thing eh ? – nivanka Jan 25 '12 at 11:24
  • I am trying this in my code but its not sorting. Just clearing my values.... – Mike Jun 10 '14 at 00:27
  • @Mike Please check the [PHP Manual](http://bd1.php.net/usort), it has few examples - http://php.net/usort – Rifat Jun 10 '14 at 10:14
  • 1
    @Mike Your sorting code is working fine. I have copied your code from the other question. Check the working code here -> http://codepad.org/YwKjeWJq I think you are having the problem somewhere else in your code, not in the sorting part. – Rifat Jun 10 '14 at 10:25
8

$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";

Sudhir Bastakoti
  • 99,167
  • 15
  • 158
  • 162
6
function bubble_sort($arr) {
    $n = count($arr);
    do {
        $swapped = false;
        for ($i = 0; $i < $n - 1; $i++) {
            // swap when out of order
            if ($arr[$i] > $arr[$i + 1]) {
                $temp = $arr[$i];
                $arr[$i] = $arr[$i + 1];
                $arr[$i + 1] = $temp;
                $swapped = true;
            }
        }
        $n--;
    }
    while ($swapped);
    return $arr;
}
Kurt Zhong
  • 7,308
  • 1
  • 19
  • 15
1
    function bubbleSort(array $arr)
    {
        $n = sizeof($arr);
        for ($i = 1; $i < $n; $i++) {
            for ($j = $n - 1; $j >= $i; $j--) {
                if($arr[$j-1] > $arr[$j]) {
                    $tmp = $arr[$j - 1];
                    $arr[$j - 1] = $arr[$j];
                    $arr[$j] = $tmp;
                }
            }
        }

        return $arr;
    }

    // Example:
    $arr = array(255,1,22,3,45,5);
    $result = bubbleSort($arr);
    print_r($result);
//====================================================
//------- improved version----------------------------
//====================================================    
function bubbleSortImproved(array $arr)
{
    $n = sizeof($arr);    
    for ($i = 1; $i < $n; $i++) {
        $flag = false;
        for ($j = $n - 1; $j >= $i; $j--) {
            if($arr[$j-1] > $arr[$j]) {
                $tmp = $arr[$j - 1];
                $arr[$j - 1] = $arr[$j];
                $arr[$j] = $tmp;
                $flag = true;
            }
        }
        if (!$flag) {
            break;
        }
    }

    return $arr;
}

// Example:
$arr = array(255,1,22,3,45,5);
$result = bubbleSortImproved($arr);
print_r($result);
Muhammad Tahir
  • 2,351
  • 29
  • 25
1

Improved Bubble Sorting enjoy :)

$sortarr = array(3,5,15,3,2,6,7,50,1,4,5,2,100,9,3,2,6,7,13,18);

    echo "<pre>";
    // Array to be sorted
    print_r($sortarr);
    // Sorted Array
    print_r(bubble_sort($sortarr));
    echo "<pre>";

    function bubble_sort($sortarr){
        // Bubble sorting
        $array_count = count($sortarr);
        for($x = 0; $x < $array_count; $x++){
            for($a = 0 ;  $a < $array_count - 1 ; $a++){
                if($a < $array_count ){
                    if($sortarr[$a] > $sortarr[$a + 1] ){
                            swap($sortarr, $a, $a+1);
                    }
                }
            }
        }
        return $sortarr;    
    }

    function swap(&$arr, $a, $b) {
        $tmp = $arr[$a];
        $arr[$a] = $arr[$b];
        $arr[$b] = $tmp;
    }
0

Maybe someone finds useful my version of Bubble Sort:

function BubbleSort(&$L) 
{  
    $rm_key = count($L);
    while( --$rm_key > -1 )#after this the very first time it will point to the last element
        for($i=0; $i<$rm_key; $i++)
            if( $L[$i] > $L[$i+1] )
                list($L[$i],$L[$i+1]) = array($L[$i+1],$L[$i]);         
} 

I got the swap idea (using list) from above comment.

Melsi
  • 1,462
  • 1
  • 15
  • 21