没有每个PHP的冒泡排序

时间:2013-09-16 06:20:23

标签: php sorting for-loop

嗨,我似乎无法让这个工作,我继续在第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>";
    }
}
?>

3 个答案:

答案 0 :(得分:5)

这是错误的:

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

$incount = 7然后$incount +1 = 8什么是未定义的...因为你只定义了7个元素......

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

答案 1 :(得分: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>";
        }
    }
}
?>

答案 2 :(得分:-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>";
}
?>