Another bubble sorting algorithm shared by PHP

  • 2021-07-13 04:44:53
  • OfStack

Classical bubble sorting method is one of the sorting methods used by many programs, saying that bubble sorting method is more efficient than PHP system function sort. This chapter does not discuss performance, so it will not be compared with system performance.

Bubble sorting roughly means comparing two adjacent numbers in turn, and then sorting them according to their size until the last two digits. Because in the sorting process, the decimal number is always put forward and the large number is put back, which is equivalent to the bubble rising, so it is called bubble sorting. But in fact, in the actual process, it can also be used in reverse according to one's own needs, with big trees put forward and decimals put back.


<?php
/**
 * PHP Use of bubble sorting method in 
 */
 
//  Advance declaration 1 Array of numbers 
$arr = array (12,45,28,30,88,67);
echo " Original array ";
print_r($arr);
echo "<br/>";
// Bubble sorting 
function maopao($arr){
  //  Conduct the first 1 Layer traversal 
  for($i=0,$k=count($arr);$i<$k;$i++) {
    //  Conduct the first 2 Layer traversal   Set each of the arrays 1 All elements are compared with outer elements 
    //  Here's i+1 It means that the outer layer traverses the following of the current element 
    for ($j=$i+1;$j<$k;$j++) {
      //  Comparison of two numbers in inner and outer layers 
        if($arr[$i]<$arr[$j]){
        //  Put it first 1 Arrays assigned to temporary variables 
          $temp = $arr[$j];
        //  Switch position 
        $arr[$j] = $arr[$i];
        //  And then assign it back from the temporary variable 
        $arr[$i] = $temp;
      }
    }
  }
  //  Returns an array after sorting 
  return $arr;
}
 
//  Print the sorted array directly 
echo ' After sorting ';
print_r(maopao($arr));
 
?>

Execute the results through the above code

Original array

Array ( [0] => 12 [1] => 45 [2] => 28 [3] => 30 [4] => 88 [5] => 67 ) 

After sorting
Array ( [0] => 88 [1] => 67 [2] => 45 [3] => 30 [4] => 28 [5] => 12 )

This is an example of bubbling method. It's simple! There is no difficulty.


Related articles: