Bubble Algorithm for sorting algorithms

Source: Internet
Author: User

The bubble algorithm is a simple sorting algorithm. It repeatedly visits the series to be sorted, compares two elements at a time, and exchanges them if their order is wrong. The work of visiting a sequence is repeated until there is no need for exchange, that is, the sequence has been sorted. The name of this algorithm comes from because the smaller elements will slowly "float" to the top of the series through the exchange.

 


Function BubbleSort ($ array ){

If (empty ($ array) |! Is_array ($ array ))

Return false;
$ Len = count ($ array)-1;
For ($ I = $ len; $ I> 0; $ I --){
For ($ j = 0; $ j <$ I; $ j ++ ){
If ($ array [$ j + 1] <$ array [$ j]) {
$ Temp = $ array [$ j];
$ Array [$ j] = $ array [$ j + 1];
$ Array [$ j + 1] = $ temp;
}
}
}
Return $ array;
}

 

 

Time Complexity: O (n * n)

 


Method 1 for improving the bubble algorithm:

If no exchange occurs in a loop, the data is sorted and the program jumps out.

Function BubbleSort2 ($ array)
{


If (empty ($ array) |! Is_array ($ array ))

Return false;


$ Len = count ($ array );
$ Ischange = false;
For ($ I = $ len-1; $ I> 0 &&! $ Ischange; $ I --)
{
$ Ischange = true;
For ($ j = 0; $ j <$ I; $ j ++)
{
If ($ array [$ j + 1] <$ array [$ j])
{
$ Temp = $ array [$ j];
$ Array [$ j] = $ array [$ j + 1];
$ Array [$ j + 1] = $ temp;
$ Ischange = false;
}
}
}
Return $ array;
}

 

 

 

 

 

 

 

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.