PHP implementation Sort algorithm----bubble sort (Bubble sort)

Source: Internet
Author: User
Basic idea:

Bubble sort is an exchange sort, and its basic idea is: 22 compare the keywords of adjacent records, if the reverse order is exchanged, until there is no reverse sequence of records. The simplest sort implementation:

Let's take a look at the sort methods that are often used before you learn all sorts of sorting methods (at least I do ...). ):

This uses type hint array, unfamiliar or not accustomed to the students can be removed, do not affect the results of the Operation
function Mysort (array & $arr) {
    $length = count ($arr) ;
    for ($i = 0; $i < $length-1; $i + +) {for
        ($j = $i + 1; $j < $length; $j + +) {
            //Put small keywords in front
            if ($arr [$i] > $a rr[$j]) {
                $temp = $arr [$i];
                $arr [$i] = $arr [$j];
                $arr [$j] = $temp;
            }

}} $arr = Array (9,1,5,8,3,7,4,6,2);
Mysort ($arr);
Print_r ($arr);

The above code, strictly speaking, is not a standard bubble sort, because it does not satisfy the bubble sort idea of "22 comparison adjacent records", it is just a simple exchange sort. The idea is just: start with the first keyword, compare each keyword with all the keywords that follow it, and swap it for the smallest value. But this algorithm is very inefficient. bubble Sort algorithm:

It repeatedly visits the sequence to be sorted, compares two elements at a time, and swaps them if their order is wrong. The task of visiting the series is repeated until no further exchange is needed, which means that the sequence has been sorted.

The name of this algorithm is because the larger elements in the array will gradually "sink" to the back of the array after sorting, and the smaller elements will gradually "float" to the front of the array, hence the name.

The bubble sort algorithm operates as follows: (forward) compares adjacent elements. If the first one is bigger than the second one, swap them both. Do the same work for each pair of adjacent elements, from the first pair to the end of the last couple. At this point, the final element should be the largest number. Repeat the above steps for all elements except the last one. Continue to repeat the previous steps for less and fewer elements until no pair of digits need to be compared.

Look at the text description does not necessarily understand, look at the code:

Swap method
function swap (array & $arr, $a, $b) {
    $temp = $arr [$a];
    $arr [$a] = $arr [$b];
    $arr [$b] = $temp;
}
Bubble sort
Function Bubblesort (array & $arr) {
    $length = count ($arr);
    for ($i = 0; $i < $length-1; $i + +) {//)
        float the small element for
        ($j = $length-2; $j >= $i; $j-) {
            //22 compare adjacent Records 
  if ($arr [$j] > $arr [$j + 1]) {
                swap ($arr, $j, $j + 1);}}}}
Bubble Sort Algorithm improvements:

"Dahua data Structure" is really a good book, we also introduced the bubble sorting algorithm improvement, here I will move its statement:

Whether the bubble sort algorithm above can be optimized. The answer is yes. Imagine if the sequence we're ordering is {2,1,3,4,5,6,7,8,9}, which means that except for the first and second keywords that need to be exchanged, everything else is in the normal order. When i = 0 o'clock, in exchange for 2 and 1, the sequence is already ordered, but the algorithm does not hesitate to execute the i = 2 to 9 and the J loops in each loop, although there is no exchange of data, but the large number of subsequent comparisons is vastly superfluous.

When i = 2 o'clock, we have compared 9 with 8,8 and 7,,3 with 2, without any data interchange, which means that this sequence is ordered and does not need to be followed by a subsequent judgment (there is no data exchange at the end of the work, and it is meaningless to do so again). To implement this idea, we need to improve the code, add a tag variable flag to implement the improved algorithm:

Swap method
function swap (array & $arr, $a, $b) {
    $temp = $arr [$a];
    $arr [$a] = $arr [$b];
    $arr [$b] = $temp;
}
/Bubble sort optimization (the entire array is already ordered if no exchange of elements occurs at one time)
function BubbleSort1 (array & $arr) {
    $length = count ($arr);
    $flag = TRUE;

    for ($i = 0; ($i < $length-1) && $flag; $i + +) {
        $flag = FALSE;
        for ($j = $length-2; $j >= $i; $j-) {
            if ($arr [$j] > $arr [$j + 1]) {
                swap ($arr, $j, $j + 1);
                $flag = TRUE;
            }}}

The key to code churn is to increase the judgment on whether the flag is true in the for loop of the I variable, and after this improvement, the bubble sort has a few enhancements in performance to avoid meaningless loops of judgment in an ordered situation.

The total time complexity of the bubble algorithm is O (n^2).

Bubble sort is a stable sort.

This blog reference from "Dahua data Structure", this only for record, convenient access later, the great God not to spray.

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.