[英]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.