PHP for Bubble Sorting

Source: Internet
Author: User

1. First, we must find out what is Bubble sorting. If we do not understand the principle of Bubble sorting, we cannot writeCode.

BubbleThe basic concept of sort is to compare two adjacent numbers in sequence, put decimal places in front, and put large numbers in the back. That is, in the first step: first compare the number of 1st and the number of 2nd, and put the decimal number before and after the large number. Then compare the numbers of 2nd and 3rd, place the decimal places before and after the large number, and continue until the last two digits are compared. Place the decimal places before and after the large number. So far, the first stop is over, and the maximum number is placed at the end. In the second round: The comparison starts from the first logarithm (because the number of 2nd is exchanged with the number of 3rd, the number of 1st is no less than 2nd). Before and after placing the decimal number, always compare to the second to the last (the largest position in the last), and the second stop, get a new maximum number at the penultimate position (in fact, it is the second largest number in the entire series ). In this case, repeat the above process until the sorting is completed.

PHP implementation code:

<? PHP  //  Bubble sorting method      Function Bubblesort (& $ Arr  ){  //  Define a variable to save the exchanged Value         $ Temp = 0 ;  For ( $ I = 0; $ I < Count ( $ Arr ); $ I ++ ){  For ( $ J = 0; $ J < Count ( $ Arr )-$ I -1; $ J ++ ){  If ( $ Arr [ $ J ]> $ Arr [ $ J + 1 ]) {  //  If the number above is greater than the number below, they will exchange                      $ Temp = $ Arr [ $ J ];  $ Arr [ $ J ] = $ Arr [ $ J + 1 ];  $ Arr [ $ J + 1] = $ Temp  ;}}}}  $ Arr = Array (,-,-7 ); Bubblesort ( $ Arr  );  Print_r ( $ Arr ); //  The array is a value transfer, so an & symbol is added during the transfer, which is the address transfer and changes the external variable. ?>

 

 

 

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.