Bubble Sorting Algorithm and bubble Algorithm

Source: Internet
Author: User

Bubble Sorting Algorithm and bubble Algorithm

The demo array is:

$ A = array (,); // The subscript is ,.

Calculation process description:

Start from the left of the array and compare the size of two adjacent data in two pairs. If the left is larger than the right, they are exchanged. After "one trip", you can determine that the largest data is placed on the rightmost.

In this way, if you continue to take the next hop on the "remaining data", you must determine that the maximum value of the remaining data is placed on the rightmost of the remaining data.

Demo:

Original array: 9 3 5 8 2 7
After the first trip: 3 5 8 2 7 9
After the second trip: 3 5 2 7 8 9
After the third round: 3 2 5 7 8 9
After the fourth round: 2 3 5 7 8 9
After the fifth tour: 2 3 5 7 8 9

 

 

 

 

 

 

Rule Description:

1. Assume that n data entries exist in the array;

2. The number of workers to be compared is n-1;

3. The number of data to be compared for each trip is one less than that for the previous trip. The first trip needs to compare n (n N-1 1 times );

4. If there is no comparison, if the "data on the left" is greater than the "data on the right", the two are switched.

The code is demonstrated as follows:

<? Php $ a = array (,); // The subscript is, echo "Before sorting:"; print_r ($ ); $ n = count ($ a); // Number of for ($ I = 0; $ I <$ n-1; ++ $ I) // This is n-1 {for ($ k = 0; $ k <$ n-$ I-1; ++ $ k) // This is the number of comparisons {if ($ a [$ k]> $ a [$ k + 1]) {$ t = $ a [$ k]; $ a [$ k] = $ a [$ k + 1]; $ a [$ k + 1] = $ t ;}} echo "<br/> after sorting: "; print_r ($ );

Running result:

Before sorting: array ([0] => 9 [1] => 3 [2] => 5 [3] => 8 [4] => 2 [5] => 7)
After sorting: array ([0] => 2 [1] => 3 [2] => 5 [3] => 7 [4] => 8 [5] => 9)

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.