Quick sorting algorithm analysis and project development algorithm analysis used in php project development _ PHP Tutorial

Source: Internet
Author: User
Quick sorting algorithm analysis and project development algorithm analysis used in php project development. Quick sorting algorithm analysis used in php project development. project development algorithm analysis this article describes the quick sorting algorithm used in php project development. For your reference, quick sort algorithm analysis and project development algorithm analysis used in php project development are provided.

This example describes the fast sorting algorithm used in php project development. We will share this with you for your reference. The details are as follows:

In fact, some algorithms are rarely used for web development. after all, it is neither a search engine nor an underlying layer (for example, writing a database similar to mysql, in addition, every language, such as java and php, has more or less encapsulated the sorting function for programmers. For example, there is a consensus that everyone understands the basics of web development. The business logic is simple and not complex. As a web development programmer, we basically use a web architecture. we add, delete, query, and modify data to databases and then display the data on pages. most of them involve performance optimization and caching.

Learning some common algorithms is helpful for implementing special applications. For example, sometimes we rely on order by in the database for sorting, so we are very accustomed to directly handing it over to the database for sorting.

Next, I need to sort it by myself.

Because we have encountered a problem in actual development, we need to sort it by myself. The requirements are as follows:

In the commodity table, there is a field goods_price (commodity price). now we need to develop a promotional price function. The promotion price has a time range. Display the product on the front-end page. If the current time meets the promotion time. The promotion price is required. Therefore, the promotion price is saved by adding a field called promote_price. the configuration information of the promotion time, such as the time, the time from the day to the time, is temporarily ignored and stored in other fields, the current time and the configured time are used to compare the display time.

When a single item is displayed, you can directly determine whether it is within the promotion time. No sorting problems.

However, when I create a commodity list page, I can find the following small details: you can choose from high to low, or choose from low to high.

If the sorting is simple, it was previously directly handed over to the database for sorting, generally, we get used to SQL statements such as "order by goods_price DESC", which can be executed in descending or ascending order of price.

Now, you cannot simply sort by goods_price (commodity price. For example, if some products in the current time meet the promotion time, the promotion price should also be sorted.

Simple order by goods_price DESC and promote_price DESC are totally different from the current requirements.

Therefore, you must first sort the order by goods_price DESC to the database to list the data.

Then, traverse to see which product data meets the promotion price. Then write your own code to achieve sorting.

My initial thought was: get the data on the current page and check whether each row meets the promotional price time point.

Foreach (results sorted by price field in the database) {if ($ v ['promote _ price']> 0 & $ promote_class-> promtoe_validate ($ food_info )) {$ v ['is _ promote'] = true; $ v ['price'] = $ v ['promote _ price']; // change the original price to the promotion price display }}

The above list, because the above list is sorted by mysql once, also goes through the promotion price. Therefore, you need to write a sorting algorithm again for sorting. In this way, we can put the lower sales price in front.

In fact, mysql databases are written in C language. I understand the database order by, which sorts the array using C language (the row list returned in the relational table is a two-dimensional array)

However, we usually deliver the sorting to the database. I rarely write it myself, so I thought these algorithms could not be used because I was not familiar with them. now I still need to use php to sort the data.

How does the order by a DESC and B ASC in the database work?

First, sort by field. Then, the data is sorted by field B.
The second understanding: sort data by field a first. if two values are the same and you cannot determine who is before, use B asc to determine the order of the two data.

I am the first kind of understanding, and later I corrected it. The second kind of understanding is correct, because it is more in line with the design considerations:

Why is it designed that multiple fields can be sorted? Is it for mutual coverage? For example, sort by field a first. If two data items are originally sorted by B asc after the previous one, the original order of the two data items may be misplaced, this may cause the result of the subsequent sorting rule to overwrite the previous one.

Assuming that database sorting is designed like this, it will be meaningless. Multiple fields are designed for sorting. To solve this problem, when the values of field a in the two rows are both 2 and 2, how can we determine the order? In this case, the following sorting rules are called to sort the two data items. Therefore, the effects of different field sequences after order by are different.

Real-life example: assume that the English scores of the 100 students are to be ranked, and the total score of the three students is 88 points. Who ranks first? In this case, a new sorting method can be added to sort the three students according to their character scores. In this way, you are sure.

The quick sorting method on the Internet is implemented for one-dimensional arrays. Now I want to simulate the rows in the database, that is, the two-dimensional array as the parameter, and can specify any field as the sorting method.

For example, if you want to query a data list from a database, you can specify a field in the list to sort it. (this is what the database needs to do. Of course, they must be more advanced. It's awesome.

For details, see the following:

/** Sorting: This function is a common function, which can be called as long as it is a two-dimensional array sorting. The original intention is to solve the rapid price sorting (involving promotional price, cannot be solved by order by) * + ---------------------------------------------------------------- * @ param $ arr to sort the array, two-dimensional arrays. It corresponds to the multi-row data array in the database (* 0 => array ("Field 1" => '', 'Field 2' => ''...) * 1 => array ("Field 1" => '', 'Field 2' => ''...) * 2 => array ("Field 1" => '', 'Field 2' => ''...) *) * + -------------------------------------------------------------------------- * @ param $ key_field indicates the field to be sorted. do not input a field that does not exist. Will disrupt the original order * + ---------------------------------------------------------------------------- * @ param $ sort_type = asc or desc sorting method. From small to large, or from large to small */function quickSort ($ arr, $ key_field, $ sort_type = "asc") {if (count ($ arr)> 1) {// which field is used for sorting. first, all the data of this field is obtained. The purpose is to convert it into a one-dimensional array for sorting. $ key_value_arr = array (); $ return_arr = array (); // Determine whether the sorted field has foreach ($ arr as $ k => $ v) {$ key_value_arr [$ k] = $ v [$ key_field]; // obtain the value of this field} // php built-in function implements descending or ascending sorting, but only supports one-dimensional array if ($ sort_type = 'desc ') {arsort ($ key_value_arr);} else {asort ($ key_value_arr);} reset ($ key_value_arr); foreach ($ key_value_arr as $ k => $ v) {$ return_arr [$ k] = $ arr [$ k]; // Get the row} return $ return_arr;} else {return $ arr ;}}

To sum up my understanding of quick sorting

If there are 100 elements, sort them. How many times does it need to be traversed? You still need to traverse at least 100 times. Because it is inevitable, scan each element one by one and drop it to the left or right. After the first split. Repeat this step on both sides after the split.
When the number of elements is small, there is no difference. If the number is large, it can contain tens of thousands of elements. The algorithm is required for sorting.
For example, in reality, we can use our eyes to see which one is smaller and then sort it out. But the computer is different. We must write a program to tell it how to implement it.

The idea of quick sorting is: divide and conquer. Split into small pieces and solve them one by one.

General Idea description:

1. find a benchmark data from a pile of data. Separated by this data standard. In reality, a bunch of 100 people are relatively short. Now I find a high person. I divide the person into groups a and B based on his height. If he is shorter than him, he will be in Group a, and even higher than him will be in Group B (which side is the same as him). In this way, 100 people can be divided into two groups.
The result is that all the people in group a must be <= persons in Group B.
2. repeat the first step for the person in Group. Repeat the first step for people in group B.
3. the group is not grouped until there is only one left (because there is no way to continue cutting.

I learned one idea: first cut into large blocks and then process them separately. Finally, the processing results of each block are merged.

Function quickSort ($ arr) {if (count ($ arr)> 1) {$ k = $ arr [0]; $ x = array (); $ y = array (); $ _ size = count ($ arr); for ($ I = 1; $ I <$ _ size; $ I ++) {if ($ arr [$ I] <= $ k) {$ x [] = $ arr [$ I]; // Small put here} else {$ y [] = $ arr [$ I]; // Large put here. This is a sort from small to large. if you want to return a result from large to small, replace the position with $ x [] = $ arr [$ I];} // The split result shows that the data on both sides of the left and right is $ x = quickSort ($ x); // The data on the left is sorted by the split method again, the returned result is the sorted data $ y = quickSort ($ y); // the right data returnarray_merge ($ x, array ($ k), $ y );} else {return $ arr ;}}

Incorrect. please correct me!

Code backup:

<? Php // general idea: because it is a two-dimensional array. Therefore, first obtain all values of the specified key. That is, it is converted to a one-dimensional array. /* However, the key of the one-dimensional array must use the key of the two-dimensional array. After sorting the one-dimensional array, it is convenient to correspond to the two-dimensional array. It depends on this key. One-dimensional array: array ('1' => 'A', '4' => 'B', '3' => 'C ', '5' => 'D'); the key values 1, 2, 4 are the evidence corresponding to the values. if you want to add a condition like SQL: order by a, B, and c when the values of field a are equal, field B is enabled for sorting. If it is still equal, enable the c field for sorting. * // * $ Keys = array (); $ keys ['GG '] = '8. 9'; $ keys [1] = '8. 8'; $ keys [5] = '7. 5'; asort ($ keys); // sorting has a feature that the original key value will not change. Just replace the bits. I thought I changed the key value. In this way, 4 reset ($ keys); var_dump ($ keys ); * // ** + sort * Fast sorting * @ author wangtao 2015.6.10 * + ------------------------------------------------------- * @ param $ arr the array to be sorted, two-dimensional array. It corresponds to the multi-row data array in the database (* 0 => array ("Field 1" => '', 'Field 2' => ''...) * 1 => array ("Field 1" => '', 'Field 2' => ''...) * 2 => array ("Field 1" => '', 'Field 2' => ''...) *) * @ param $ key_field sort by which field * @ param $ sort_type = asc or desc sort method. From small to large, or from large to small * + --------------------------------------------------------- * return is a new array sorted according to the specified order. The original key will still be retained * for example: 1 => array ("Field 1" => '', 'Field 2' => ''...), 2 => array ("Field 1" => '', 'Field 2' => ''...) * after sorting by "field 2", if the key is a 2 element, it may be in front of it, but the key value will not be modified and will be retained as is * + ------------------------------------- */function quick_sort, $ key_field, $ sort_type = "asc") {if (count ($ arr)> 1) {// which field is used for sorting, first obtain all data of this field, the purpose is to convert it into a one-dimensional array for sorting $ key_value_arr = array (); $ return_arr = array (); // first checks whether the sorted field exists. if the field does not exist, avoid disrupting the order of the original array forea Ch ($ arr as $ k =>$ v) {@ $ key_value_arr [$ k] = $ v [$ key_field]; // obtain the value of this field} // php built-in function implements descending or ascending sorting, but only supports one-dimensional array if ($ sort_type = 'desc ') {arsort ($ key_value_arr);} else {asort ($ key_value_arr);} reset ($ key_value_arr); foreach ($ key_value_arr as $ k => $ v) {$ return_arr [$ k] = $ arr [$ k]; // get row} // var_dump ($ return_arr); return $ return_arr ;} else {return $ arr; }}$ array = array ('name' => 'cell phone ', 'brand '=> 'Nokia', 'price' => 1050), array ('name' => 'laptop ', 'brand' => 'Lenovo ', 'price' => 4300), array ('name' => 'shares', 'brand' => 'Phillips', 'price' => 3100 ), array ('name' => 'Treadmill ', 'brand' => 'three', 'price' => 4900), array ('name' => 'Watch ', 'brand' => 'case', 'price' => 960), array ('name' => 'LCD TV', 'brand' => 'Sony ', 'price' => 6299), array ('name' => 'laser printer ', 'brand' => 'HP', 'price' => 1200 ), array ('name' => 'phone', 'brand' => 'Nokia ', 'price' => 1050),); var_dump (quickSort ($ Array, 'M'); // you can see how the elements in an array are sorted with null values. $ row = array (0 => null, 1 => null, 2 => null, 3 => null,); asort ($ row); var_dump ($ row); // if it is null. Is it based on the key value? /* The returned result is array 3 => null 2 => null 1 => null 0 => null. now I understand whether the database field is null, which affects sorting. The results will affect the display effect. */

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.