我在python中进行了合并排序,工作正常,我尝试在PHP中重新创建逻辑,但它无法正常工作。这是python代码:
def merge(array):
if len(array) > 1:
arrayL = []
arrayR = []
for i in range(int(len(array)/2)):
arrayL.append(array[i])
for i in range(int(len(array)/2),len(array)):
arrayR.append(array[i])
arrayL = merge(arrayL)
arrayR = merge(arrayR)
left = right = insert = 0
while left < len(arrayL) and right < len(arrayR):
if arrayL[left] < arrayR[right]:
array[insert] = arrayL[left]
left += 1
else:
array[insert] = arrayR[right]
right += 1
insert += 1
while left < len(arrayL):
array[insert] = arrayL[left]
left += 1
insert += 1
while right < len(arrayR):
array[insert] = arrayR[right]
right += 1
insert += 1
return array
这是来自shell:
>>> merge([23,21,5,111,32,11,7,1,45])
[1, 5, 7, 11, 21, 23, 32, 45, 111]
这是PHP代码:
function merge($array) {
$arrayLength = count($array);
if ($arrayLength > 1) {
$arrayLeft = array_slice($array, 0, $arrayLength/2);
$arrayRight = array_slice($array, $arrayLength/2);
$arrayLeft = merge($arrayLeft);
$arrayRight = merge($arrayRight);
$left = 0;
$right = 0;
$insert = 0;
while ($left < count($arrayLeft) and $right < count($arrayRight)){
if ($arrayLeft[$left] < $arrayRight[$right]) {
$array[$insert] = $arrayLeft[$left];
$left += 1;
} else {
$array[$insert] = $arrayRight[$right];
$right += 1;
}
$insert += 1;
}
while ($left < count($arrayLeft)) {
$array[$insert] = $arrayLeft[$left];
$left += 1;
$insert += 1;
}
while ($right < count($arrayRight)) {
$array[$insert] = $arrayRight[$right];
$right += 1;
$insert += 1;
}
return $array;
}
}
print_r(merge(array(23,21,5,111,32,11,7,1,45)));
这就是它的输出:
Array ( [0] => 1 [1] => 5 [2] => 23 [3] => 21 [4] => 32 [5] => 11 [6] => 45 [7] => 45 [8] => 111 )
非常感谢任何帮助
答案 0 :(得分:1)
return $array;
语句应在if
范围之外。