问题描述
据我所知,这两个程序应该做的完全一样。但是,Python版本有效,而PHP版本无效。我想念什么?
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);
推荐答案
排序实际上是可行的,但您却不这样做传递对 bubble_sort($ arr)
函数的引用,您将永远看不到实际结果。告诉 bubble_sort()
通过引用传递数组意味着您正在更改 $ my_list
而不是 $ 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
哦,您使用 $ arr [i]
而不是 $ 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
这篇关于在PHP和Python中进行冒泡排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!