PHP bubble sorting algorithm details

Source: Internet
Author: User

The sorting process is as follows:
49 38 65 97 76 13 27
38 49 65 97 76 13 27 compare the number of 1st and 2nd, Small put the front side, large put behind 38 49 65 97 76 13 27 compare the number of 2nd and 3rd, small front side, large back side 38 49 65 97 76 13 27 Comparison 3rd and 4th number, small front side, the large side is 38 49 65 76 97 13 27 compared with 4th and 5th numbers. The small side is the front side, 38, 49, 65, 76, 13, 97, and 27 are larger than 5th and 6th, put the big back 38 49 65 76 13 27 97 compare the number of 6th and 7th, put the small front side, put the big back at this point, the first stop comparison, get the following order: 38 49 65 76 13 27 97
The comparison is continued based on the first sorting method until the sorting is completed.

Column 1

The code is as follows: Copy code

$ Arr = array (234 );
For ($ I = 1; $ I <count ($ arr); $ I ++ ){
For ($ j = count ($ arr)-1; $ j >=$ I; $ j --){
If ($ arr [$ j] <$ arr [$ j-1]) {
$ Temp = $ arr [$ j-1];
$ Arr [$ j-1] = $ arr [$ j];
$ Arr [$ j] = $ temp;
}
}
}

Column 2

The code is as follows: Copy code

/**
* Php bubble sorting algorithm implementation
* @ Param array $ array one-dimensional array
* @ Return array the sorted array
*/
Function bsort (array $ array ){
$ Count = count ($ array );
If ($ count = 0 ){
Return array ();
} Elseif ($ count = 1 ){
Return $ array;
} Elseif ($ count> 1 ){
For ($ I = 0; $ I <$ count; $ I ++ ){
For ($ j = $ count-1; $ j> $ I; $ j --){
If ($ array [$ j] <$ array [$ j-1]) {
$ Temp = $ array [$ j];
$ Array [$ j] = $ array [$ j-1];
$ Array [$ j-1] = $ temp;
                }
            }
        }
Return $ array;
} Else {
Return false;
    }
}

$ Arr = array );
Print_r (bsort ($ arr ));

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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.