-1

嗨,我似乎无法让它工作,我在第 8 行和第 11 行中不断收到未定义的错误。这是我的代码

<?php
$count = 0;
$temp = 0;
$name = array("Suzuki", "Holden", "Jaguar", "Toyota", "Hyundai", "Ford", "Honda", "Mazda");
echo $name[0] . " " . $name[1] . " " . $name[2] . " " . $name[3] . " " . $name[4] . " " . $name[5] . " " . $name[6] . " " . $name[7] . "<p>";
for ($incount = 0; $incount <= 7; $incount++) {
    if ($name[$incount] > $name[$incount + 1]) {
        $temp = $name[$incount];
        $name[$incount] = $name[$incount + 1];
        $name[$incount + 1] = $temp;
        echo $name[0] . " " . $name[1] . " " . $name[2] . " " . $name[3] . " " . $name[4] . " " . $name[5] . " " . $name[6] . " " . $name[7] . $count++ . "<p>";
    }
}
?>
4

3 回答 3

5

这是错误:

$name[$incount] > $name[$incount + 1]

什么时候对你来说是未定义的......因为你只定义了 7 个元素$incount = 7......$incount +1 = 8

解决方案可以只是$incount < 7

于 2013-09-16T06:23:13.267 回答
2

您没有使用正确的冒泡排序算法。它需要两个循环。

<?php
$count = 0;
$temp = 0;
$name = array("Suzuki", "Holden", "Jaguar", "Toyota", "Hyundai", "Ford", "Honda", "Mazda");
echo $name[0] . " " . $name[1] . " " . $name[2] . " " . $name[3] . " " . $name[4] . " " . $name[5] . " " . $name[6] . " " . $name[7] . "<p>";
for ($incount = 0; $incount <= 7; $incount++) {
    for ($innercount = $incount+1; $innercount <= 7; $innercount++) {
        if ($name[$incount] > $name[$innercount]) {
            $temp = $name[$incount];
            $name[$incount] = $name[$innercount];
            $name[$innercount] = $temp;
            echo $name[0] . " " . $name[1] . " " . $name[2] . " " . $name[3] . " " . $name[4] . " " . $name[5] . " " . $name[6] . " " . $name[7] . $count++ . "<p>";
        }
    }
}
?>
于 2013-09-16T06:36:06.487 回答
-1
<?php
$count = 0;
$temp = 0;
$name = array("Suzuki", "Holden", "Jaguar", "Toyota", "Hyundai", "Ford", "Honda", "Mazda");
echo $name[0] . " " . $name[1] . " " . $name[2] . " " . $name[3] . " " . $name[4] . " " . $name[5] . " " . $name[6] . " " . $name[7] . "<p>";
for ($incount = 0; $incount < 8; $incount++) {
    if(isset($name[$incount + 1]))
    if ($name[$incount] > $name[$incount + 1]) {
        $temp = $name[$incount];
        $name[$incount] = $name[$incount + 1];
        $name[$incount + 1] = $temp;}
        echo $name[0] . " " . $name[1] . " " . $name[2] . " " . $name[3] . " " . $name[4] . " " . $name[5] . " " . $name[6] . " " . $name[7] . $count++ . "<p>";

}
?>

但更好用

<?php
$count = 0;
$temp = 0;
$name = array("Suzuki", "Holden", "Jaguar", "Toyota", "Hyundai", "Ford", "Honda", "Mazda");
foreach($name as $f) echo $f." ";
echo "<p>";
for ($incount = 0; $incount < 8; $incount++) {
    if(isset($name[$incount + 1]))
    if ($name[$incount] > $name[$incount + 1]) {
        $temp = $name[$incount];
        $name[$incount] = $name[$incount + 1];
        $name[$incount + 1] = $temp;}
        foreach($name as $f) echo $f." ";
        echo  $count++ . "<p>";
}
?>
于 2013-09-16T06:29:43.650 回答