A collection of PHP classic algorithms

Source: Internet
Author: User
Tags pow
This article mainly introduces the PHP classic algorithm collection, sorting out a variety of common algorithms, including sorting, lookup, traversal, arithmetic and other common algorithm principles and implementation skills, the need for friends can refer to the next

This paper summarizes the classic PHP algorithm. Share to everyone for your reference, as follows:

1, first to draw a diamond to play, a lot of people learn C in the book are painted, we use PHP painting, draw half.

Idea: How many lines for once, then inside spaces and asterisks for once.


<?phpfor ($i =0; $i <=3; $i + +) {  echo str_repeat ("", 3-$i);  echo str_repeat ("*", $i *2+1);  Echo ' <br/> ';}


2, bubble sort, C-base algorithm, from small to large to a group of numbers sort.

Idea: This problem from small to large, the first round of the smallest, the second round the second small, third-round row third small, and so on ...


<?php$arr = Array (1,3,5,32,756,2,6), $len = count ($arr), for ($i =0; $i < $len-1; $i + +) {for  ($j = $i +1; $j < $len; $j + +) {    if ($arr [$i]> $arr [$j]) {//From small to large      $p = $arr [$i];      $arr [$i] = $arr [$j];      $arr [$j]= $p;    }}}  Var_dump ($arr);


3, Yang Hui Triangle, written in PHP.

Idea: Each line of the first and last one is 1, no change, the middle is the front row and the left row of the and, the algorithm is a two-dimensional array to save, another algorithm with a one-dimensional array can also be implemented, a line of output, there is interest to write the play.

1
1 1
1 2 1
1 3 3 1
1 4 6) 4 1
1 5 10 10 5 1


<?php//the first and last of each line is 1, 6 lines for ($i =0; $i <6; $i + +) {  $a [$i][0]=1;  $a [$i] [$i]=1; }//out the first and last values, save in the array for ($i =2; $i <6; $i + +) {for  ($j =1; $j < $i; $j + +) {   $a [$i] [$j] = $a [$i -1][$j -1]+ $a [$ i-1][$j];  } }//Print for ($i =0; $i <6; $i + +) {for  ($j =0; $j <= $i; $j + +) {  echo $a [$i] [$j]. ' ';  }  Echo ' <br/> '; }


4, in a group of numbers, required to insert a number, in its original order inserted, maintain the original sorting method.

Idea: Find a location that is larger than the number you want to insert, replace it, and then move the back number back one bit.


<?php$in = 2; $arr = Array (1,1,1,3,5,7), $n = count ($arr);//If the number to be inserted is the largest, print if ($arr [$n-1] < $in) {  $arr [$n +1] = $ In Print_r ($arr);  } for ($i =0; $i < $n; $i + +) {//Find out where to insert  if ($arr [$i] >= $in) {    $t 1= $arr [$i];    $arr [$i] = $in;//move back data back one for    ($j = $i +1; $j < $n +1; $j + +) {      $t 2 = $arr [$j];      $arr [$j] = $t 1;      $t 1 = $t 2;  } Print  print_r ($arr);  Die;  }}


5. Sort a set of numbers (fast sorting algorithm).

Idea: The two parts are divided into two sections by a trip, and then they are sorted recursively and finally merged.


<?phpfunction Q ($array) {  if (count ($array) <= 1) {return $array;} The $key is divided into two sub-arrays  $key = $array [0];  $l = Array ();  $r = Array (),//recursively sort, and then synthesize an array for  ($i =1; $i <count ($array); $i + +) {  if ($array [$i] <= $key) {$l [] = $arra y[$i]; }  else {$r [] = $array [$i];}}  $l = q ($l);  $r = q ($r);  Return Array_merge ($l, Array ($key), $r);} $arr = Array (1,2,44,3,4,33);p Rint_r (q ($arr));


6. Find the element you want in an array (binary lookup algorithm).

Idea: A value in the array is bounded and then recursively searched until the end.


<?phpfunction Find ($array, $low, $high, $k) {  if ($low <= $high) {  $mid = intval (($low + $high)/2);    if ($array [$mid] = = $k) {    return $mid;  } ElseIf ($k < $array [$mid]) {    return find ($array, $low, $mid-1, $k);    } else{    return Find ($array, $mid +1, $high, $k);    }  }  Die (' not having ... ');} Test$array = Array (2,4,3,5), $n = count ($array); $r = Find ($array, 0, $n, 5)


7, merging multiple arrays, without Array_merge (), the topic to the Forum.

Idea: Iterate through each array and re-form a new array.


<?phpfunction T () {  $c = Func_num_args ()-1;  $a = Func_get_args ();  Print_r ($a);  for ($i =0; $i <= $c; $i + +) {    if (Is_array ($a [$i])) {for      ($j =0; $j <count ($a [$i]); $j + +) {        $r [] = $a [$i] [$j ];      }    } else {die      (' not a array! ');    }  }  return $r;} Testprint_r (t (range (1,4), Range (1,4), Range (1,4)), Echo ' <br/> ', $a = Array_merge (range (1,4), Range (1,4), Range (1,4));p rint_r ($a);


8, the year of the Ox: there is a cow, to 4 years of age can be fertile, one day, the birth are the same cow, to 15-year-old sterilization, no longer able to live, 20-year-old death, asked how many cows in n years. (from the Forum)


<?phpfunction T ($n) {    static $num = 1 for    ($j =1; $j <= $n; $j + +) {        if ($j >=4 && $j <15) {$ Num++;t ($n-$j);}        if ($j ==20) {$num--;}     }     return $num;} Testecho T (8);


==================== Other Algorithms =========================

Bubble sort (bubble sort)-O (N2)


$data = Array (3,5,9,32,2,1,2,1,8,5);d UMP ($DATA); Bubblesort ($data);d UMP ($data), function Bubblesort (& $arr) {$limit = count ($arr); for ($i =1; $i < $limit; $i + +) { For  ($p = $limit-1; $p >= $i; $p-)  {  if ($arr [$p-1] > $arr [$p])  {   $temp = $arr [$p-1];   $arr [$p-1] = $arr [$p];   $arr [$p] = $temp;  }}}  } function Dump ($d) {echo ' <pre> ';p rint_r ($d); Echo ' </pre> ';}


Insert sort (Insertion sort)-O (N2)


$data = Array (6,13,21,99,18,2,25,33,19,84), $nums = count ($data) -1;dump ($data), Insertionsort ($data, $nums);d UMP ($ Data), Function Insertionsort (& $arr, $n) {for ($i =1; $i <= $n; $i + +) {  $tmp = $arr [$i]  ; for ($j = $i; $j >0 && $arr [$j -1]> $tmp; $j--)  {  $arr [$j] = $arr [$j-1];  }  $arr [$j] = $tmp;}} function Dump ($d) {echo ' <pre> ';p rint_r ($d); Echo ' </pre> ';}


Hill sort (shell sort)-O (n log n)


$data = Array (6,13,21,99,18,2,25,33,19,84), $nums = count ($data);d UMP ($DATA); Shellsort ($data, $nums);d UMP ($data), function Shellsort (& $arr, $n) {for ($increment = Intval ($n/2); $increment > 0 ; $increment = Intval ($increment/2)) {for  ($i = $increment; $i < $n; $i + +)  {  $tmp = $arr [$i];  for ($j = $i; $j >= $increment; $j-= $increment)   if ($tmp < $arr [$j-$increment])   $arr [$j] = $arr [$j-$inc Rement];   else break   ;  $arr [$j] = $tmp;  }}} function Dump ($d) {echo ' <pre> ';p rint_r ($d); Echo ' </pre> ';}


Quick Sort (quicksort)-O (n log n)


$data = Array (6,13,21,99,18,2,25,33,19,84);d UMP ($DATA), quicks ($data, 0,count ($data)-1);d UMP ($data), function dump ($ Data) {echo ' <pre> ';p rint_r ($data); Echo ' </pre> ';} Function QuickSort (& $arr, $left, $right) {$l = $left; $r = $right; $pivot = Intval (($r + $l)/2); $p = $arr [$pivot];d o{  while ($arr [$l] < $p) && ($l < $right))  $l + +;  while ($arr [$r] > $p) && ($r > $left))  $r--;  if ($l <= $r)  {  $temp = $arr [$l];  $arr [$l] = $arr [$r];  $arr [$r] = $temp;  $l + +;  $r--;  }} while ($l <= $r), if ($left < $r)  QuickSort (& $arr, $left, $r), if ($l < $right)  QuickSort (& $arr, $l, $right);}


=================================================

Bubble sort: 22 Exchange values, the minimum value on the leftmost, as the lightest bubbles at the top. For the whole column number 22 exchange once, the smallest number on the leftmost, each can get a minimum number in the remaining number, "take" out of the number of an ordered interval, the remaining values constitute an unordered interval, and the order interval of each element value is smaller than the disordered interval.

Quick sort: Datum number, left and right two arrays, recursive call, merge.

Insertion sort: The sorting interval is divided into two parts, the left is ordered, the right is unordered, the right interval takes the first element into the left interval, if this element is larger than the right-most element of the left interval, and remains in place, if this element is smaller than the rightmost element on the left, then the rightmost element is inserted at the right, and the , repeat the above steps until the previous element is smaller than the element you want to insert.

Note that the interval endpoint value is processed, and the first element of the array is labeled 0.


<?php//php Common sorting algorithm function Bubblesort ($array) {$n = count ($array); for ($i = 0; $i < $n; $i + +) {for ($j = $n-2; $j &G T;= $i;  $j-)//[0,i-1] [I,n-1]{if ($array [$j] > $array [$j + 1]) {$temp = $array [$j]; $array [$j] = $array [$j + 1]; $array [$j + 1] = $temp;}}} return $array;} $array = Array (3,6,1,5,9,0,4,6,11);p Rint_r (Bubblesort ($array)), Echo ' 


=======================================


<?php/* "Insert sort (one-dimensional array)" "Basic idea": each time a data element to be sorted is inserted into the appropriate position in the previously ordered sequence, the sequence remains orderly until all the data elements to be sorted are inserted. "Example": [Initial keywords] [[]] 49j=2 (+) [38] (+) [49] (+)] (+) [49j=3] [97] [49j=5] [*] [] [] 49j=6 (49) [] [all] [] [] [all] [] 49j=7 (+) [] [97]*/function Insert_sort ($arr) {$count = count ($arr); for ($i =1; $i < $count; $i + +) {$tmp = $arr [$i]  ;  $j = $i-1;   while ($arr [$j] > $tmp) {$arr [$j +1] = $arr [$j];   $arr [$j] = $tmp;  $j--; }}return $arr;} /* "Select sort (one-dimensional array)" "Basic idea": Each trip selects the smallest (or largest) element from the data element to be sorted, placing the order at the end of the ordered sequence until all the data elements to be sorted are exhausted. "Example": [Initial keyword] [49 38 65 97 76 13 27 49] First trip sort 13 [38 65 97 76 49 27 49] The second order 13 27 [65 97 76 49 38 49] The third order after 13 27 38 [9 7 76 49 65 49] Fourth order 13 27 38 49 [49 97 65 76] Fifth trip sort 13 27 38 49 49 [97 97 76] Sixth trip sort 13 27 38 49 49 76 [76 97] Seventh trip sort after 13 27 38 49 49 76 76 [97] The final ranking results of 97*/function Select_sort ($arr) {$count = count ($arr); for ($i = 0; $i < $count;  $i + +) {$k = $i;  for ($j = $i +1; $j < $count; $j + +) {if ($arr [$k] > $arr [$j]) $k = $j;}    if ($k! = $i) {$tmp = $arr [$i];    $arr [$i] = $arr [$k];  $arr [$k] = $tmp; }}return $arr;} /* "bubble sort (one-dimensional array)" "Basic idea": 22 Compare the size of the data elements to be sorted, and find that the two data elements are exchanged in reverse order until there are no reversed data elements. "Sort procedure": Imagine the sorted array r[1. N] vertically erected, each data element as a weight of the bubble, according to the light bubbles can not under the principle of heavy bubbles, from the bottom up scan array r, where scanning to violate the principle of light bubbles, so that it "floating upward", so repeated, until the last two bubbles are light in the upper, heavy in the next.  "Example": 49 13 13 13 13 13 13 1338 49 27 27 27 27 27 2765 38 49 38 38 38 38 3897 65 38 49 49 49 49 4976 97 65 49 49 49 49 4913 The 6527 of the 7649, the 97*/function bubble_sort ($array) {$count = count ($array), and I F ($count <= 0) return false;for ($i =0; $i < $count; $i + +) {for ($j = $count-1; $j > $i; $j-) {if ($array [$j] < $a    rray[$j-1]) {$tmp = $array [$j];    $array [$j] = $array [$j-1];   $array [$j-1] = $tmp; }}}return $array;} /* "Quick sort (one-dimensional array)" "Basic idea": any data element in the current unordered area R[1..h] as the "datum" of the comparison (which may be remembered as X), using this datum to divide the current unordered division into the left and right two smaller unordered areas: r[1..i-1] and R[i 1..H], and the left of noneThe data elements in the order sub-region are less than or equal to the datum elements, and the data elements in the unordered sub-extents on the right are greater than or equal to the datum elements, while the Datum X is in the final sort position, i.e. r[1..i-1]≤x.key≤r[i 1..H] (1≤i≤h), when R[1..i-1] and r[i 1..H] are not empty, each of them is divided into the above process until all the data elements in the unordered sub-extents are sorted. "Example": initial keyword [49 38 65 97 76 13 27 49] After the first Exchange [27 38 65 97 76 13 49 49] After the second exchange [five] 49]j left scan, position unchanged, after the third Exchange [27 Five 49]i to scan to the right, position unchanged, after the fourth exchange [three years of the 49]j to scan to the left [27 38 13 49 76 97 65 49] (one division process) Initial keywords [49 38 65 97 76 13 27 49] After a trip [27 38 13] 49 [76 97 65 49] Two [13] 27 [38] 49 [49 65]76 [97] Three order 13 27 38 49 49 [65]76 97 Final Sort Result 13 27 38 49 49 65 76 97 Status */function quick_sort ($array) {if (count ($array) <= 1) return $array; $key = $array [0]; $l Eft_arr = Array (), $right _arr = Array (), for ($i =1, $i <count ($array), $i + +) {if ($array [$i] <= $key) $left _arr[] =  $array [$i]; else $right _arr[] = $array [$i];} $left _arr = Quick_sort ($left _arr); $right _arr = Quick_sort ($right _arr); return Array_merge ($left _arr, Array ($key), $ Right_arr);} /* Print array full contents */function Display_arr ($array) {$len = count ($array); foR ($i = 0; $i < $len; $i + +) {echo $array [$i]. ' ';} echo ' <br/> ';} /* Comparison and selection of several sorting algorithms 1. The factors to be considered in the sorting method are: (1) The number of elements to be sorted n, (2) the size of the elements ' information, (3) The structure and distribution of the keywords, and (4) the conditions of the language tools, the size of the auxiliary space, etc. 2. Summary: (1) If n is small (n <= 50), you can use direct insert sort or directly select sort. Since the record moving operation required for direct insertion of the sort is more than the direct selection, so when the information of the record itself is large, it is better to sort by direct selection. (2) If the initial state of the file has been basically ordered by the keyword, the choice of direct insertion or bubble sort is advisable. (3) If n is larger, it should be sorted by the time complexity O (nlog2n): Quick sort, heap sort, or merge sort. Fast sorting is considered to be the best method in the current comparison based internal sorting method. (4) in the comparison based on the method, each time the size of the two keyword is compared, only two possible transitions, so you can use a binary tree to describe the comparison process, which can prove that: when the file's n keyword randomly distributed, any with the help of "comparison" sorting algorithm, at least O (nlog2n ) of the time. (5) When the information of the record itself is large, in order to avoid the time-consuming movement of the record, the linked list can be used as the storage structure. *//* Sort Test */$a = array (' n ', ' 4 ', ' + ', ' 8 ', ' + ', ' + ', ' 5 ', ' + '); Echo ' The result of insert sort: '; $insert _a = Insert_sort ($a );d Isplay_arr ($insert _a); Echo ' The result of select sort: '; $select _a = Select_sort ($a);d Isplay_arr ($select _a); Echo '  The result of bubble sort: '; $bubble _a = Bubble_sort ($a);d Isplay_arr ($bubble _a); Echo ' The result of bubble sort: '; $quick _a = Quick_sort ($a);d Isplay_arr ($quick _a);? >



/** * permutation combination * Using binary method to combine the selection, such as 5 select 3 o'clock, only 3 bits 1 is OK, so the available combination is 01101 11100 00111 10011 01110 10 Kinds of combinations * * @param array $arr * @param minimum number $min _size * @return new array combination */function pl ($arr, $size =5) {$len = Coun T ($arr); $max = POW (2, $len); $min = POW (2, $size)-1; $r _arr = Array ();  for ($i = $min; $i < $max; $i + +) {$count = 0;  $t _arr = Array ();  for ($j =0; $j < $len; $j + +) {$a = POW (2, $j);  $t = $i & $a;   if ($t = = $a) {$t _arr[] = $arr [$j];  $count + +;  }} if ($count = = $size) {$r _arr[] = $t _arr; }} return $r _arr;  } $PL = pl (Array (1,2,3,4,5,6,7), 5), Var_dump ($PL),///recursive algorithm//factorial function f ($n) {if ($n = = 1 | | $n = = 0) {return 1;  }else{return $n *f ($n-1);  }}echo f (5);//Traverse directory function iteral ($path) {$filearr = array (); foreach (Glob ($path. '    \* ') as $file) {if (Is_dir ($file)) {$filearr = Array_merge ($filearr, Iteral ($file));    }else{$filearr [] = $file; }} return $filearr;} Var_dump (iteral (' d:\www\test ')); 

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.