Bubble sort (Bubble sort)

Source: Internet
Author: User

The common sorting algorithms are bubble sort, Merge sort, Quick sort, and so on, all of the Basic Law ideas of sorting are to reduce the size of an infinite scale of data through the algorithm, to guide the final completion of the sorting.

Here to share the buuble sort algorithm, PHP version. Bubble sort does not fit in the case where the data set to be sorted is particularly large, this is just a simple demo, and the data to be sorted is within 10.

The algorithm complexity of the bubbling sorting algorithm, which is caused by 2 extreme cases, is different:

    1. All datasets are ordered, at this point the algorithm can be optimized by the complexity of the algorithm from O (n^2) to O (n)
    2. All datasets are unordered, and the complexity of the algorithm is O (n^2)

Beginners seldom consider when writing bubble sort, and if the data itself is an ordered data set, the complexity of the algorithm is O (n^2) if it is not optimized.

Here is the PHP version of the 2 notation:

First Kind

1 functionBubblesort ($arr,$n){2 $swap;//defining the best algorithm for swap resolution3  for($i= 0;$i<$n-1;$i++ ){4     $swap=false; 5      for($j= 0;$j<$n-$i;$j++){ 6         if($arr[$j] >$arr[$j+1]){7             $tmp=$arr[$j];8             $arr[$j] =$arr[$j+1];9             $arr[$j+1] =$tmp;Ten             $swap=true; One         }    A         $k++;  -     }    -         if($swap==false) the                  Break1; -  } -}

The second Kind

1 functionNewbubblesort ($arr,$n){2      Do {3         $sorted= 1;4--$n;5          for($i= 0;$i<$n;$i++){6             if($arr[$i] >$arr[$i+1]){7                 $t=$arr[$i];8                 $arr[$i] =$arr[$i+1];9                 $arr[I+1] =$t;Ten                 $sorted= 0; One             } A         } -} while(!$sorted); -}

Optimizes the bubble sorting algorithm by defining a flag bit.

Bubble sort (Bubble sort)

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.