Robin - 25 days ago 4x
PHP Question

# 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):
for passnum in range(len(alist)-1,0,-1):
for i in range(passnum):
if alist[i]>alist[i+1]:
temp = alist[i]
alist[i] = alist[i+1]
alist[i+1] = temp

my_list = [2,3,5,4,1]
bubbleSort(my_list)
print(my_list)

<?php
// Bubble Sort
\$my_list = [2,3,5,4,1];

function bubble_sort(\$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]){
swap(\$arr, \$arr[i], \$arr[\$i+1]);
}
}
}
}

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

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

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];

function bubble_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);
}
}
}
}

function swap(&\$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

Source (Stackoverflow)