简体   繁体   中英

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

Bubble Sort Php

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

function bubble_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>';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM