简体   繁体   中英

Bubble Sort Logic

The swapping logic on the below code, is not constructive. A single value inside the array is fixed that is compared with the other array. If found greater then the arrays are swapped.

<?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 */ 

    }

}
?>  

It seems like that you are trying to implement the bubble sort algorithm.

Here is a correct solution:

$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
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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