PHP's second play-application of classic algorithms (bubble sorting and quick sorting)

Source: Internet
Author: User
First of all, let's talk about the idea of bubble sorting. many colleagues will ask what is bubble sorting? Next I will explain: the so-called bubble sorting method is to compare two adjacent numbers in sequence, put the decimal points in front, and put the large numbers in the back. That is, first, compare the number of 1st and 2nd, and put the decimal point before the large number... SyntaxHighlighter. all ();

First of all, let's talk about the idea of bubble sorting. many colleagues will ask what is bubble sorting?


I will explain it below:

The so-called bubble sorting method compares two adjacent numbers in sequence, placing decimals in front, and placing 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.


Let's look at an example:
There is an array (, 89). next we will use the bubble sort method to sort its elements.
$ Arr = Array (, 89 );
For ($ I = 0; $ I For ($ j = 0; $ j If ($ arr [$ j]> $ arr [$ j + 1]) {
$ Tmp = $ arr [$ j];
$ Arr [$ j] = $ arr [$ j + 1];
$ Arr [$ j + 1] = $ tmp;
}
}
}
?>

In the preceding example, the for loop compares all the elements in this array by two, that is, comparing the first element in the array with the second element, compared with the third element,
Until the last element of the array is compared with the last element, if the previous element is greater than the next element, the previous element is exchanged with the next element,
So how can we change the positions of two elements in the array,
We can use an intermediate container variable to solve this problem,
That is, to put the value of the first variable to be exchanged into the container variable, and then assign the value of the second variable to be exchanged to the first variable, then, assign the value in the container variable to the second variable.


For a deeper understanding, see the following figure:

Step 1: declare an intermediate container variable $ tmp:

Step 2: assign the value of $ arr [$ j] to $ tmp

Step 3: assign $ arr [$ j + 1] to $ arr [$ j].

Step 4: assign the value of the intermediate variable to $ arr [$ j + 1] to complete the exchange

And so on until the last and last elements of the array are compared. count ($ arr)-1 times in total
So far, the first sorting of our array is complete, and the maximum number in the array has been placed at the end of the array. that is to say, the for loop in the inner layer has been executed. www.2cto.com
Next we need to take the second and third trip .... sort each row, and place the maximum number behind the array. after sorting, the total number of rows is count ($ arr.
Speaking of this, do you understand the meaning of the outer for loop!
Well, let's think about a problem. if the elements in the array are compared to each other, the maximum number is exceeded for each comparison,
In the next comparison, will we not compare it with the maximum number shown in the previous comparison,
That is to say, 98 has been placed at the end of the array after the first sorting, and 98 does not need to be compared in the next sorting, which will improve efficiency and save resources,
Therefore, we can write as follows:
$ Arr = Array (, 89 );
For ($ I = 0; $ I For ($ j = 0; $ j If ($ j = count ($ arr)-1 ){
Continue;
}
If ($ arr [$ j]> $ arr [$ j + 1]) {
$ Tmp = $ arr [$ j];
$ Arr [$ j] = $ arr [$ j + 1];
$ Arr [$ j + 1] = $ tmp;
}
}
}
?>

In the above code, the number of inner loop executions is changed to count ($ arr)-$ I,
That is to say, after each row compares all elements in the array, the number of sorting times is reduced by one when the next row sorts again,
That is, to exclude the comparison of the maximum number obtained by the previous comparison. as a result, the efficiency will be improved a lot,
We can use the php built-in function microtime () to execute the sorting once before it is executed, and then execute the sorting once to subtract the two times to get the computing time,
Through comparison, we can conclude that the efficiency of the second sort method of bubble sorting is higher than that of the first sort method, but it is not very obvious. we can verify it and we will not talk about it here.

Next we use the quick sort method to sort the above arrays:
$ Arr = Array (, 89 );
Function quick ($ arr ){
$ Left = array ();
$ Right = array ();
If (count ($ arr) <= 1 ){
Return $ arr;
}
For ($ I = 1; $ I If ($ arr [0]> $ arr [$ I]) {
$ Left [] = $ arr [$ I];
} Else {
$ Right [] = $ arr [$ I];
}
}
$ Left = quick ($ left );
$ Right = quick ($ right );
Return array_merge ($ left, array ($ arr [0]), $ right );
}
?>


The so-called quick sorting means to take any value in the $ arr array as the middle value, and then compare this value with all other elements in the array, put it to the left if it is smaller than this value, put a value greater than this value to the right of this value, and complete the sorting. similarly, sort the number on the left of the value and sort the number on the right. until all values are compared.

Let's look at the above code:
First, the concept of fast sorting requires recursion. when it comes to recursion, the function calls itself, goes deeper layer by layer, and finally returns the value.
Next let's take a look. First, we need to customize a function quick () so that this function can call itself.
Here, we use $ arr [0] for the median value. this is random and not required,
To make everyone's thinking clearer, we first define two empty arrays, which is equivalent to two cups,
Compare $ arr [0] with all values in the array, and place values smaller than $ arr [0] in the first Cup, put the image larger than $ arr [0] into the second cup. in the program, the values are $ left and $ right, respectively,
If the given array element has only one or null, the array will be returned by the quick function and the following content will not be executed,
Next, we traverse the array and compare the retrieved values with $ arr [0] respectively. values smaller than $ arr [0] are saved to the $ left array, a value greater than $ arr [0] is saved to the $ right array. this completes sorting,
Next, perform the same operation on the $ left array and $ right array, that is, call the function itself and pass in the $ left array and $ right array, when an array element in the $ left array or $ right array is one, you do not need to call yourself and return it directly,
Finally, combine the array on the left, $ arr [0], and $ right to obtain the final sorting result.

Fixed:
Corrected the efficiency problem. An error occurred during the test efficiency, resulting in inaccurate efficiency tests. After reminders, the test was conducted again and again, in the end, we found that the efficiency of the quick sort operation for sorting this array is similar to that of the bubble sort, but the first one of the bubble sort is obviously higher than the second one, this test result can only be used as a reference. to accurately calculate the efficiency of each algorithm, you need to calculate the number of sorting times within the algorithm.
Thanks again for your attention and rectification of this issue. this is an open platform. please speak freely, communicate more, and make common progress...



From zdrjlamp

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.