繁体   English   中英

冒泡排序逻辑

[英]Bubble Sort Logic

以下代码的交换逻辑不具建设性。 数组中的单个值是固定的,它与另一个数组进行比较。 如果发现更大,则交换 arrays。

<?php   
$a=array(13,12,11,10,9,8,7); /* array initialised */ 
$length=count($a);           /* To Count the length of the array */
for($i=0;$i<=$length;$i++){  /* Loop to hold the first index of the number */ 

    $temp=$a[$i];            /* To store the number the  first value of the array on variable */

    for($j=1;$j<=$length;$j++){  /* Second loop to check all the remaining values */

            if($a[$i]>$a[$j]){   /* condtion to check if the first index number is larger than others */

                $temp1=$a[$i];  
                $a[$i]=$a[$j];  /* swapping of numbers with postions */
                $a[$j]=$temp1;  /* swapping of numbers with postions */
            }
            break;              /* To exit the nested loop */ 

    }

}
?>  

您似乎正在尝试实现冒泡排序算法。

这是一个正确的解决方案:

$arr=array(13,12,11,10,9,8,7);

$n = sizeof($arr);

// Traverse through all array elements
for($i = 0; $i < $n; $i++)
{
    // Last i elements are already in place
    for ($j = 0; $j < $n - $i - 1; $j++)
    {
        // traverse the array from 0 to n-i-1
        // Swap if the element found is greater
        // than the next element
        if ($arr[$j] > $arr[$j+1])
        {
            $t = $arr[$j];
            $arr[$j] = $arr[$j+1];
            $arr[$j+1] = $t;
        }
    }
}

output:

Array
(
    [0] => 7
    [1] => 8
    [2] => 9
    [3] => 10
    [4] => 11
    [5] => 12
    [6] => 13
)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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