A fast sorting algorithm used in PHP project development _php Techniques

Source: Internet
Author: User
Tags arrays php language php programming php regular expression

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

In fact, do web development, less than encounter the use of some algorithms and so on, after all, not to do search engines, nor write the bottom (such as writing a database similar to MySQL, which needs to implement their own sorting algorithm), in addition, each language, such as Java, PHP is more or less already encapsulating the sort function for programmers to use. For example, there is a consensus, we do the basic web development understand that the business logic is more simple, not very complex business logic. We as a web developer programmer, basically is the Web architecture, the database additions and deletions to check the data, and then show the data in the page, most of it involves performance optimization, caching and so on.

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

Next, I came across the need to implement the sort myself.

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

In the commodity table, there is a field is goods_price (commodity price), now to develop a promotional price function. Promotional price has a time range set. In the front page, show the product. If the current time matches the promotional time. Should be carried out according to the promotional price. Therefore, the promotion price alone added a field to save, called Promote_price, promotional time configuration information such as what time, how many times each day, such as time settings information temporarily, stored in other fields, display, to use the current time and configure the time to compare.

When a single item is displayed, it is directly judged whether it is within the promotional time. No sort problem encountered.

But in doing the Product List page, one such small details let me find the demand: Users can choose the price of goods in accordance with "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, and generally we are accustomed to using SQL in the "ORDER by Goods_price DESC" such as statements can be implemented in descending or ascending prices.

Now, it's not easy to sort by goods_price (commodity price) OK. For example, the current time some goods are in line with promotional time, then the promotional price is also to be sorted.

The simple order by Goods_price Desc,promote_price DESC This practice is entirely wrong with the current demand for the road.

So, you need to first sort the order by Goods_price DESC to the database, listing the data.

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

My initial idea was: get the current page of the data, which determines whether each line meets the promotional price point of time

foreach (Results sorted by database 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 above list, because the list above is sorted by MySQL once, also after the promotion price. So you need to write a sort algorithm once again. So we can put the promotion price down to the front.

In fact, the MySQL database is written in C language. I understand the database order by, which is the sort that uses the C language to sort the array (the list of rows returned in the relational table is a two-dimensional array).

Just, usually we sort is to the database to achieve. Rarely write their own, so because the contact is not much, it is thought that these algorithms do not use, now still need to use the PHP language to achieve the order of data.

The implementation principle of the order by a desc,b ASC in the database guess?

The first kind of understanding: first sort by the a field. The data is then sorted by the B field.
The second understanding is that by first sorting by a field, if two values are the same and you cannot determine who is in front, then b ASC is used to determine the order of two data.

I was the first to understand, then corrected, the second understanding is correct, because this is more in line with the design considerations:

Why would you want to design multiple fields for sorting? Is it to cover each other out? For example, the first is sorted by a field. If one of the two data is originally a previous one, and if you sort by b ASC, then the order of the two data may be misplaced, which may result in the previous collation being applied.

It is meaningless to assume that database ordering is such a design. Multiple fields are designed to be sorted. is in order to solve, encountered two rows in the value of a field is 2,2, how to determine successively? This is the time to sort the two data by calling the following collation. So the effect is different when the order of the fields is different.

Real life Example: Suppose to rank 100 students in English, assuming the sort of time, encountered three students are 88 points. Who ranked in front of it? This time it is possible to attach a new sort of arrangement to the three students to see their conduct sorted. That's a good way to be sure.

The fast sorting method on the Internet is implemented for one-dimensional arrays. Now I'm going to simulate rows in a database, a two-dimensional array as a parameter, and you can specify any field as a sort.

For example, from the database to query out a list of data, intact on this list can specify a field to sort (the database is to achieve this requirement.) Of course they have to be more advanced. Some people are better than others.

Specifically, look at the following:

/* Sort: This function is a universal function, as long as the order of the two-dimensional array can be called. The original intention is to solve the price of a quick sort (involving promotional prices, cannot use order by resolution) * +--------------------------------------------------------------------------* @param $arr The array to sort, the two-dimensional array.
 The corresponding is a multiline 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 according to which field to sort, Do not pass in a field that does not exist. Will disrupt the original order * +--------------------------------------------------------------------------* @param $sort _type = ASC or des C Sorting 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 is all data, the purpose is to convert to a one-dimensional array to sort $key _value_arr = array ();
    $return _arr = Array (); First determine whether the sorted field exists a foreach ($arr as $k => $v) {$key _value_arr[$k] = $v [$key _field];//Get the value of this field}//php built-in function 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 line} return $return _arr;
  else {return $arr;

 }
}

To sum up my understanding of the fast sorting method

Let's say you have 100 elements to sort this out. So how many times do you need to traverse? Still need to traverse at least 100 times. Because it does not avoid, one by one to scan each element, throw to the left, or to the right. After the first split. You will continue to repeat this step on 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. Needs to be sorted, it involves an algorithm
For example, compared to the height, the reality of the 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 method to implement.

The idea that the quick sort manifests is: divide the law. Split into small pieces and solve them one by one.

General description of the idea:

1, from a pile of data to find a benchmark data. Separated by this data standard. Realistic example, a pile of people 100 people, relatively tall. Now I'm going to find a person of high altitude, and I'm going to a,b two groups according to the height of this person. Those who are shorter than him stand in group A and stand to B (as tall as he can on either side), which can divide 100 people into two groups.
As a result, all of the people in Group A have to <=b in the group.
2. Repeat the first step to the people in Group A. Repeat the first step for the people inside Group B.
3, until the end of only one (because it has not been able to continue cutting), the group.

I learned a thought: cut into chunks first and then handle each chunk individually. 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 side
   }else{
    $y [] = $arr [$i] //The big place is here. This is a small to large sort, if you want to return from large to small, then swap position and $x[] = $arr [$i]; the location of the
   split appears to be the left and right sides of the data
  $x = QuickSort ($x); On the left, the data is sorted again using the Split method, and the result is the sorted data
  $y = QuickSort ($y);//Right Data
  Returnarray_merge ($x, Array ($k), $y);
 } else{
  Return$arr
 }
}

The wrong place, please correct me!

Code Backup:

<?php//General idea: by a two-dimensional array. So get all the values for the specified key first.
That is, converting to a one-dimensional array. /* However, the key of this one-dimensional array is to use the key of the two-dimensional array. After such a one-dimensional array is sorted, it is convenient to correspond to the two-dimensional array.
This is the key.
The one-dimensional array is as follows: Array (' 1 ' => ' A ', ' 4 ' => ' B ', ' 3 ' => ' C ', ' 5 ' => ' d '); 1,2,4 these key values, then is the corresponding to the inside of the evidence to think, if you need to add a condition such as SQL: ORDER by A,b,c when the value of a field is equal, enable the B field to sort.
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 has a feature, the original key value will not change. Just change the position. I thought it was an exchange of key values.
This way, 0,1,2,3,4 Reset ($keys);
Var_dump ($keys); * * * * +-------------------------------------------------------* Quick order * @author Wangtao 2015.6.10 * +--------------- ----------------------------------------* @param $arr the array to sort, the two-dimensional array.
 The corresponding is a multiline 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 to sort by which field * @param $sort _type = ASC or desc sort. From large to large, or from large to small * +-------------------------------------------------------* Return a new array after the specified sort. The original key is stillWill retain * such as: 1=>array ("Field 1" => ', ' Field 2 ' => ' ...), 2=>array ("Field 1" => ', ' Field 2 ' => ' ...)
* after "Field 2" sorted, the key 2 element may be in front, but the key value will not be modified, will be retained * +-------------------------------------------------------* * function Quick_sort ($arr, $key _field, $sort _type = "ASC") {if (count ($arr) > 1) {//using which field to sort, get all the data for the field first, to convert to a one-dimensional
    Array is sorted $key _value_arr = Array ();
    $return _arr = Array (); First determine if the sorted field exists, if the field does not exist, avoid disrupting the order of the original array foreach ($arr as $k => $v) {@ $key _value_arr[$k] = $v [$key _field];
    The value of this field}//php built-in function implements descending or ascending order, but supports only one-dimensional arrays 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 ' => ' Razor ', ' Brand ' => ' Philips ', ' Price ' =>3100), Array (' name ' => ' treadmill ', ' brand ') => ' Three and pine rock ', ' 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 ' =
> ' mobile ', ' Brand ' => ' Nokia ', ' price ' =>1050);
Var_dump (QuickSort ($array, ' m '));
Look at how the element values are empty in an array $row = Array (0=>null, 1=>null, 2=>null, 3=>null,);
Asort ($row); Var_dump ($row);//If Empty.
is the key value reversed? /* Returns the array 3 => NULL 2 => null 1 => NULL 0 => NULL now finally understands whether the database field remains null and has an effect on the sort.
The results will affect the presentation effect.

 */

More interested in PHP related content readers can view the site topics: "PHP Sorting algorithm Summary", "PHP object-oriented Program Design Primer", "PHP Mathematical Arithmetic Skills summary", "PHP operation Office Document Skills Summary (including word,excel,access, ppt), "PHP array" operation Skills Encyclopedia, "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 will help you with the PHP program design.

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.