Another PHP-implemented bubble sort algorithm to share _php instances

Source: Internet
Author: User

The classic bubble sort method has been one of the sorts used by many programs, saying that the bubble sort method is more efficient than the PHP system function sort. This chapter does not discuss performance, so do not compare it to the system.

Bubble sort probably means to compare adjacent two numbers sequentially and then sort by size until the last two digits. Because the decimal is always pushed forward in the sort process, the large number is placed backward, which is the equivalent of a bubble going up, so called bubble sort. But in fact in the actual process can also be in accordance with their own needs in turn, the tree forward, the decimal place back.

 The bubble sort method in <?php/** * PHP uses
 the
 
///Advance declaration of an array
$arr = Array (12,45,28,30,88,67);
echo "original array";
Print_r ($arr);
echo "<br/>";
Bubble sort
Function Maopao ($arr) {
  //For first-level traversal for
  ($i =0, $k =count ($arr); $i < $k; $i + +) {
    //second-level traversal Compare each element in an array with the outer element
    //The i+1 meaning here is for
    ($j = $i +1; $j < $k; $j + +) {
      //inner-outer Layer two number comparison
        if ($arr [$i ]< $arr [$j]) {
        //First assign one of the arrays to a temporary variable
          $temp = $arr [$j];
        Swap position
        $arr [$j] = $arr [$i];
        Then assign the value from the temporary variable
        $arr [$i] = $temp;
  }}} Returns the sorted array return
  $arr;
 
Direct print sort after array of
echo ' sort ';
Print_r (Maopao ($arr));
 
>

Execute results with the above code

Original array

Copy Code code as follows:
Array ([0] => [1] => [2] => [3] => [4] => [5] => 67)

After sorting
Copy Code code as follows:
Array ([0] => [1] => [2] => [3] => [4] => [5] => 12)

This is the Bubble Method example, simple! Without the difficulty of God horse.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.