PHP bubble sorting program code and source code

Source: Internet
Author: User

Introduction to bubble sorting:

Bubble Sort is a simple sorting algorithm in the computer science field.
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.

How the bubble sorting algorithm works:

Compares adjacent elements. If the first is bigger than the second, exchange the two of them.
Perform the same operation on each adjacent element, from the first to the last. At this point, the final element should be the largest number.
Repeat the preceding steps for all elements except the last one.
Continue to Repeat the above steps for fewer and fewer elements until there is no need to compare them.

PHP code example:

The code is as follows: Copy code

$ A = array ('3', '8', '1', '4', '11', '7 ');
Print_r ($ );
$ Len = count ($ );
// From small to large
For ($ I = 1; $ I <$ len; $ I ++)
{
For ($ j = $ len-1; $ j >=$ I; $ j --)
If ($ a [$ j] <$ a [$ j-1])
{// If it is from large to small, just change the judgment here to if ($ B [$ j]> $ B [$ j-1]).
$ X = $ a [$ j];
$ A [$ j] = $ a [$ j-1];
$ A [$ j-1] = $ x;
         }
}

Let's look at another one.

The code is as follows: Copy code

<? Php
# Bubble sorting
$ Arr = array (28,112, 20,434, 65,765, 33,553, 45,423 );
$ Tmp;
For ($ I = 0; $ I <count ($ arr)-1; $ I ++ ){
For ($ j = 0; $ j <count ($ arr)-1-$ I; $ j ++ ){
If ($ arr [$ j]> $ arr [$ j + 1]) {
$ Tmp = $ arr [$ j];
$ Arr [$ j] = $ arr [$ j + 1];
$ Arr [$ j + 1] = $ tmp;
        }
    }
}
 
 
Print_r ($ arr );

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.