Analysis of fast sorting algorithm used in PHP project development, analysis of Project development algorithm _php tutorial

Source: Internet
Author: User
Tags php regular expression

Analysis of fast sorting algorithm used in PHP project development and analysis of project development algorithm


This paper describes the fast sorting algorithm used in PHP project development. Share to everyone for your reference, as follows:

In fact, to do web development, less than the use of some algorithms, after all, not to do search engines, nor write the bottom (such as a database like MySQL, the need to implement the sorting algorithm), in addition, each language, such as Java, PHP is more or less packed with sorting functions for programmers. For example, there is a consensus, we do the basic understanding of web development, business logic is more simple, not very complex business logic. We as a web development programmer, basically is the Web architecture, the database additions and deletions to change data, and then display the data in the page, mostly involving performance optimization, caching and so on.

Learning some common algorithms is helpful for implementing special applications. For example, sometimes we rely on the database of order by to achieve the sort, so very accustomed to directly to the database implementation of the order.

Then I came across the need to sort it out for myself.

Because we are in real development, encountered a problem, completely need my own implementation of the sort. The requirements are as follows:

In the commodity table, there is a field is goods_price (commodity price), now to develop a promotional price function. The promotion price has a time range setting. In the foreground page, when the product is displayed. If the current time matches the promotion time. will be carried out according to the promotion price. So the promotion price alone added a field to save, called Promote_price, promotional time configuration information such as what time, every day to a few times the time set information temporarily regardless, stored in other fields, when displayed, to use the current time with the configured time to compare.

When a single item is displayed, it is directly judged whether it is within the promotion time. Did not encounter a sorting problem.

But in the Product List page, a little detail like this let me find the need: The user can choose the price of goods according to "from High to Low" can also choose "from low to high" sort.

If it is a simple sort, the past is directly to the database to sort, generally we are accustomed to SQL in the use of "ORDER by Goods_price DESC" statements such as can be achieved in descending or ascending order of price.

Now, you can't simply sort by goods_price (commodity price) OK. For example, the current time some products are in line with the promotion time, then the promotional price is to be sorted.

Simple ORDER by Goods_price Desc,promote_price DESC This approach is completely wrong with the current demand for the road.

So, the data needs to be sorted once for the order by Goods_price DESC that is handed to the database.

Then traverse to see which product data is in line with the promotional price. Then write your own code to implement the sort.

My initial idea was: get the data from the current page and determine if each line meets the promotional price point in time

foreach (Result of database sorted by Price field) {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    }}

For the list above, because the list above is sorted by MySQL once, it also passes the promotion price. So you also need to write a sorting algorithm once again. So we can put the promotion price low to the front.

In fact, MySQL database is written in C language. I understand the database order by, and it's sort of using C to sort the array (the list of rows returned in the relational table is a two-dimensional array)

Just, usually our sort is handed to the database to achieve. Rarely write their own, so because the contact is not much, I think these algorithms themselves, and still need to use the PHP language to achieve sorting data.

How does the implementation of order by a desc,b ASC in the database guess?

First understanding: Sort by the A field first. The data is then sorted by the B field.
Second understanding: Sort by the A field first, if you encounter two values that are the same, you cannot determine who is in the previous post, then use B ASC to determine the order of two data.

I am the first to understand, then correct, the second understanding is right, because it is more in line with the design considerations:

Why design can you sort multiple fields? Is it to cover each other out? For example, sort by the a field first. If a two-item data is originally in the previous one, and if it is sorted by the B ASC, then it is possible that the order of the two data may be misplaced, which may result in the result of subsequent collation application overwriting the previous.

It doesn't make sense to assume that the database sort is designed like this. Multiple fields are designed to be sorted. is to solve, encountered two lines in the value of a field is 2,2, how to determine successively? At this point, the following collation is called to sort the two data. Therefore, the order by the field after the sequence of different results are different.

Real life Example: Suppose to rank 100 students in English scores, assuming the sort of time, met three students are 88 points. Who ranked in front of it? This time you can add a new sort to the three students to see their character sorted. That's a good way to be sure.

The fast ordering method on the Internet is implemented for one-dimensional arrays. Now I want to simulate a row in a database, which is a two-dimensional array as an argument, and you can specify any field as a sort.

For example, from the database to query a list of data, unchanged to the list can specify a field to sort (the database is to achieve this requirement.) Of course they have to be more advanced. Somebody else is a little more.

Specifically, see below:

/* Sort: This function is a generic function that can be called whenever a two-dimensional array is sorted. The original intention is to resolve the price quick sort (related to the promotional price, cannot be resolved by using ORDER BY) * +--------------------------------------------------------------------------* @param $arr the array to be sorted, two-dimensional array. The corresponding is the multi-row data in the database array (* 0=>array ("field 1" = ", ' field 2 ' = = ' ...) * 1=>array (" field 1 "=", ' field 2 ' = = ' ...) * 2=> Array ("Field 1" = ", ' field 2 ' = = ' ...) *) * +----------------------------------------------------------------------- ---* @param $key _field which field to sort by, do not pass in a field that does not exist. Will disrupt the original order * +--------------------------------------------------------------------------* @param $sort _type = ASC or Desc Sort method. From large to large, or from large to small */function quickSort ($arr, $key _field, $sort _type = "ASC") {if (count ($arr) > 1) {//Use which field to sort, first get the field    There is data to be converted into a one-dimensional array to sort $key _value_arr = array ();    $return _arr = Array (); First determine if the sorted field exists foreach ($arr as $k + $v) {$key _value_arr[$k] = $v [$key _field];//Get the value of this field}//php built-in function implementation    is sorted in descending or ascending order, but only one-dimensional array is supported 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 line} return $return _arr;  } else {return $arr; }}

Summarize my understanding of the quick Sort method

Suppose there are 100 elements to sort this. So how many times do you need to traverse? You still need to traverse at least 100 times. Because it is inevitable, to scan each element individually, to the left, or to the right. After the first split. You also continue to repeat this step for both sides of the split.
When the number of elements is small, the difference is not realized. If the number is large, it reaches tens of thousands of elements. Need to be sorted, you need to involve the algorithm
For example, relatively tall, realistic situation, we can see with the eyes, which is smaller, and then think of the sort out. But computers are different. We have to write a program to tell it what the method is to be implemented.

The idea of quick sequencing is: divide and conquer the law. Split into small pieces, resolved one by one.

A general description of the idea:

1, from a pile of data to find a benchmark data. Separated by this data standard. Realistic example, a bunch of people 100 people, relatively tall. Now I find a height of people, I according to this person's height, divided into a group of two groups. He was shorter than he stood in group A, taller than he stood to B (as high as he casually on which side can be), this way can be divided into two groups of 100 people.
As a result, all the people in Group A are <=b in the group.
2. Repeat the first step for the person in Group A. Repeat the first step for the people in Group B.
3, until the end of only one (because it is not able to continue cutting), only group.

I learned a thought: cut into chunks first, then treat each chunk individually. Finally, the processing results of each block are merged together.

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 Place this way   }else{    $y [] = $arr [$i];/ /Big put this way. This is the order from small to large, if you want to return from large to small, then swap position with $x[] = $arr [$i]; the position can   }   //Get split the data  $x = QuickSort ($x);// The data on the left is sorted again using the Split method, and the result is the sorted data  $y = QuickSort ($y);//Data returnarray_merge on the right  ($x, Array ($k), $y);} else{  Return$arr;}}

The wrong place, please correct me!

Code Backup:

<?php//general idea: By then a two-dimensional array. So get all the values for the specified key first. That is, converting to a one-dimensional array. /* But the key of this one-dimensional array is to use the key of the two-dimensional array. This makes it easy to correspond to a two-dimensional array after sorting the one-dimensional array. Just rely on this key. The one-dimensional array is as follows: Array (' 1 ' = = ' A ', ' 4 ' = ' = ' B ', ' 3 ' = ' C ', ' 5 ' = ' d '); 1,2,4 these key values, that is the evidence that corresponds to the inside to think, If you want to add a condition like sql: ORDER by a,b,c enables the B field to be sorted when the value of the A field is equal. If it is still equal, the C field is enabled for sorting. *//* $keys = Array (); $keys [' gg '] = ' 8.9 '; $keys [1] = ' 8.8 '; $keys [5] = ' 7.5 '; Asort ($keys);//Sort with a feature, the original key value will not change. Just change the position. I thought I was swapping the key value. This way, 0,1,2,3,4reset ($keys); Var_dump ($keys); *//* * +-------------------------------------------------------* Quick Sort * @ Author Wangtao 2015.6.10 * +-------------------------------------------------------* @param $arr to sort the array, two-dimensional array. The corresponding is the multi-row data in the database array (* 0=>array ("field 1" = ", ' field 2 ' = = ' ...) * 1=>array (" field 1 "=", ' field 2 ' = = ' ...) * 2=> Array ("Field 1" = "', ' field 2 ' = = ' ...) *) * @param $key _field by which field to sort * @param $sort _type = ASC or desc sort method. From small to large, or from big to small * +-------------------------------------------------------* Return followed by a new array of the specified sort. The original key will still remain * such as: 1=>array ("field 1" = ","Field 2 ' = + ' ...), 2=>array ("field 1" = = ", ' field 2 ' = = ' ...) * After sorting by "Field 2", the key 2 element may be in front, but the key value will not be modified and will remain as-is * +-------------------------------------------------------*/ function Quick_sort ($arr, $key _field, $sort _type = "ASC") {if (count ($arr) > 1) {//Use which field to sort, first get all the data for that field to convert to a one-dimensional array    Sort $key _value_arr = array ();    $return _arr = Array (); First determine if the sorted field exists, if the field does not exist at all, avoid disrupting the order of the original array foreach ($arr as $k = = $v) {@ $key _value_arr[$k] = $v [$key _field];//Get this    The value of the field}//php built-in functions are implemented in descending or ascending order, but only one-dimensional arrays are supported 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 ' + ' phone ', ' brand ' = ' Nokia ', ' Price ' =>1050), Array (' name ' = ' "laptop ', ' brand ' = ' Lenovo ', ' Price ', ' =>4300 ', Array (' name ' = ' razor ', ' brand ' = ' Philips ', ' priCe ' =>3100), Array (' name ' = = ' treadmill ', ' brand ' = ' three and ' pine stone ', ' price ' =>4900), Array (' name ' = ' watch ', ' brand ' = ') Casio ', ' 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 ')); how to sort $row = Array (0=>null,1=>null,2=>null,3=>null,) if the element values inside an array are empty; Asort ($ row); Var_dump ($row);//If Empty. Then the value is reversed according to the key? /* Returns array 3 + NULL 2 = null 1 = NULL 0 = NULL Now it's clear that the database field remains null and has an effect on sorting. The results will affect the display effect. */

More about PHP related content readers can view the topic: "Summary of PHP sorting algorithm", "PHP Object-oriented Programming tutorial", "PHP Math Skills Summary", "PHP operation Office Document Skills Summary (including word,excel,access, ppt), "php array", "PHP Data structure and algorithm tutorial", "PHP Programming Algorithm Summary", "PHP Regular Expression Usage Summary", and "PHP Common database Operation Skills Summary"

I hope this article is helpful to you in PHP programming.

http://www.bkjia.com/PHPjc/1138978.html www.bkjia.com true http://www.bkjia.com/PHPjc/1138978.html techarticle The fast sorting algorithm analysis used in PHP project development and the analysis of the project development algorithm This paper describes the fast sorting algorithm used in PHP project development. Share to everyone for reference, with ...

  • 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.