Skip to content Skip to sidebar Skip to footer

Bubble Sort In Php And Python

As far as I can tell, these two programs should do exactly the same thing. However, the Python version works and the PHP one doesn't. What am I missing please? def bubbleSort(alist

Solution 1:

The sort is in fact working, but as you dont pass a reference to the bubble_sort($arr) function you never get to see the actual result. Telling bubble_sort() that the array is being passed by reference means you are changing $my_list and not a copy of $my_list

Oh and you had some compile errors, using $arr[i] instead of $arr[$i]

// Bubble Sort$my_list = [2,3,5,4,1];

functionbubble_sort(&$arr){    // <-- changed to &$arr$size = count($arr);
    for($pass_num = $size - 1; $pass_num >= 0; $pass_num--){
        for($i = 0; $i < $pass_num; $i++){
            if($arr[$i] > $arr[$i + 1]){
                // also changed this line to pass just the indexes
                swap($arr, $i, $i+1);   
            }
        }
    }
}


functionswap(&$arr, $a, $b) {
    $tmp = $arr[$a];
    $arr[$a] = $arr[$b];
    $arr[$b] = $tmp;
}

bubble_sort($my_list);
print_r ($my_list);

If you are testing this on a live server where error reporting is turned off add these lines to the top of any script you are developing, while you are developing it.

<?php
error_reporting(E_ALL); 
ini_set('display_errors', 1);

And the compile errors would have shown on the web page

Solution 2:

Bubble Sort Php

$data_set = [3,44,38,5,15,26,27,2,46,4];

functionbubble_sort($data_set){
    $number_of_items = count($data_set);
    for($i = 0; $i <= $number_of_items - 2; $i++){
        for($j = 0; $j <= $number_of_items -($i+2); $j++){
            if($data_set[$j] > $data_set[$j + 1]){
                $temp = $data_set[$j];
                $data_set[$j] = $data_set[$j + 1];
                $data_set[$j + 1] = $temp;
            }
        }
    }
    return$data_set;
}


echo'<pre>';
print_r(bubble_sort($data_set));
echo'</pre>';

Post a Comment for "Bubble Sort In Php And Python"