# Classic PHP algorithm Collection [classic favorites], classic php algorithm collection

Source: Internet
Author: User

Classic PHP algorithm Collection [classic favorites], classic php algorithm collection

This example summarizes the classic PHP algorithm. We will share this with you for your reference. The details are as follows:

1. First, draw a diamond for fun. Many people have painted it in books when learning C. We have used PHP to draw half of it.

Idea: How many rows for once, and then the space and star number for once in it.

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

2. Bubble Sorting: Basic Algorithms in C, sorted by a group of numbers from small to large.

Idea: This question is from small to large, the first round is the smallest, the second round is the second, the third is the third, and so on ......

`<? Php \$ arr = array (, 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: the first and last bits of each row are 1, with no changes. The middle is the sum of the first bits in the front row and the last bits on the left. This algorithm is saved using a two-dimensional array, in addition, there is an algorithm that can be implemented using a one-dimensional array. The output of a row is interesting to write and 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 rows are both 1, and 6 rows for (\$ I = 0; \$ I <6; \$ I ++) are written) {\$ a [\$ I]  = 1; \$ a [\$ I] [\$ I] = 1;} // returns the values except the first and last bits, 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 set of numbers, insert a number in the original order to maintain the original sorting method.

Idea: Find the location that is larger than the number to be inserted, replace it, and then move the following number one.

`<? Php \$ in = 2; \$ arr = array (,); \$ n = count (\$ arr); // if the maximum number of inserts is exceeded, print if (\$ arr [\$ n-1] <\$ in) {\$ arr [\$ n + 1] = \$ in; print_r (\$ arr );} for (\$ I = 0; \$ I <\$ n; \$ I ++) {// locate the position to be inserted if (\$ arr [\$ I] >=\$ in) {\$ t1 = \$ arr [\$ I]; \$ arr [\$ I] = \$ in; // move the subsequent data to one for (\$ j = \$ I + 1; \$ j <\$ n + 1; \$ j ++) {\$ t2 = \$ arr [\$ j]; \$ arr [\$ j] = \$ t1; \$ t1 = \$ t2;} // print print_r (\$ arr); die ;}}`

5. Sort a group of numbers (quick sorting algorithm ).

Idea: sort the two parts by one click, recursively sort the two parts, and merge them.

`<? Phpfunction q (\$ array) {if (count (\$ array) <= 1) {return \$ array;} // bounded by \$ key, it is divided into two sub-arrays \$ key = \$ array ; \$ l = array (); \$ r = array (); // recursive sorting is performed respectively, then synthesize an array for (\$ I = 1; \$ I <count (\$ array); \$ I ++) {if (\$ array [\$ I] <= \$ key) {\$ l [] = \$ array [\$ I];} else {\$ r [] = \$ array [\$ I] ;}\$ l = q (\$ l ); \$ r = q (\$ r); return array_merge (\$ l, array (\$ key), \$ r) ;}\$ arr = array (1, 2, 4, 3, 4, 33 ); print_r (q (\$ arr ));`

6. Search for the elements you need in an array (Binary Search Algorithm ).

Idea: Use a value in the array as the boundary, and then perform recursive search 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 have...');}//test\$array = array(2,4,3,5);\$n = count(\$array);\$r = find(\$array,0,\$n,5)`

7. Merge multiple arrays without using array_merge.

Idea: traverse each array and 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));print_r(\$a);`

8. Every year, a cow has the same birth as a 4-year-old cow. It is sterilized at the age of 15 and no longer gives birth to a 20-year-old cow, ask how many cows are there in n years. (From 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-O (n2)

`\$data = array(3,5,9,32,2,1,2,1,8,5);dump(\$data);BubbleSort(\$data);dump(\$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>';print_r(\$d);echo '</pre>';}`

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);dump( \$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>';print_r(\$d);echo '</pre>';}`

Shell sort-O (n log n)

`\$data = array(6,13,21,99,18,2,25,33,19,84);\$nums = count(\$data);dump( \$data );ShellSort(\$data,\$nums);dump( \$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-\$increment];   else   break;  \$arr[\$j] = \$tmp;  }}}function dump( \$d ){echo '<pre>';print_r(\$d);echo '</pre>';}`

Quicksort-O (n log n)

`\$data = array(6,13,21,99,18,2,25,33,19,84);dump(\$data);quicks(\$data,0,count(\$data)-1);dump(\$data);function dump( \$data){echo '<pre>';print_r(\$data);echo '</pre>';}function QuickSort(& \$arr,\$left,\$right){\$l = \$left;\$r = \$right;\$pivot = intval((\$r+\$l)/2);\$p = \$arr[\$pivot];do{  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 Sorting: exchange values by two. The smallest value is on the leftmost side, just as the lightest bubble is on the top. The number of the entire column is exchanged for one time. The smallest number is on the leftmost side. Each time, a minimum number in the remaining number is obtained, and an array popped up into an ordered interval, the remaining values constitute an unordered interval, and each element value in the ordered interval is smaller than that in the unordered interval.

Quick sorting: the number of baselines, two arrays left and right, recursively called, and merged.

Insert sorting: the sorting interval is divided into two parts. The order on the left and the order on the right are unordered. The first element from the right is inserted into the left interval. If this element is larger than the element on the far right of the Left interval, if the element is smaller than the element on the rightmost side of the left edge range, it is inserted in the original position of the rightmost element. At the same time, the rightmost element is shifted to one place, and the calculator minus one, repeat the preceding steps to repeat the previous steps until the previous element is smaller than the element to be inserted.

Note the processing of the range endpoint value and the subscript of the first element of the array is 0.

```<? Php // PHP common Sorting Algorithm function bubblesort (\$ array) {\$ n = count (\$ array); for (\$ I = 0; \$ I <\$ n; \$ I ++) {for (\$ j = \$ n-2; \$ j >=\$ 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 (, 9, 0, 11); print_r (bubblesort (\$ array); echo '
========================================================
<? Php/* [insert sort (one-dimensional array)] [basic idea]: Insert a data element to be sorted into the appropriate position in the sequence that has already been sorted, the sequence is still ordered until all elements of the data to be sorted are inserted. [Example]: [initial keyword]  38 65 97 76 13 27 49J = 2 (38) [38 49] 65 97 76 13 27 49J = 3 (65) [38 49 65] 97 76 13 27 49J = 4 (97) [38 49 65 97] 76 13 27 49J = 5 (76) [38 49 65 76 97] 13 27 49J = 6 (13) [13 38 49 65 76 97] 27 49J = 7 (27) [13 27 38 49 65 76 97] 49J = 8 (49) [13 27 38 49 49 65 76 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]: selects the smallest (or largest) element from the data element to be sorted, the sequence is placed at the end of the sorted series until all the data elements to be sorted are arranged. [Example ]: [initial keyword] [49 38 65 97 76 13 27 49] after the first round of sorting 13 [38 65 97 76 49 27 49] after the second round of sorting 13 27 [65 97 76 49 38 49] 13 27 38 after the third round sorting [97 76 49 65 49] 13 27 38 49 after the fourth round sorting [49 97 65 76] 13 27 38 after the fifth round sorting 49 49 [97 97 76] 13 27 38 49 49 49 76 [76 97] 13 27 38 49 49 49 76  The Last sorting result 13 27 38 49 49 76 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 ]: compare the size of the elements to be sorted. If the two data elements are in the opposite order, they are exchanged until there is no reverse order of the data elements. [Sorting process]: Imagine the sorted array R [1 .. n] vertical erect, each data element is considered as a bubble with weight, according to the principle that light bubbles cannot be under heavy bubbles, scanning array R from bottom up, when a light bubble that violates this principle is scanned, it is made to "float" up, so it is repeated until the last two bubbles are both light and heavy. [Example ]: 49 13 13 13 13 13 13 13 1338 49 27 27 27 2765 38 38 38 38 38 3897 65 38 49 49 49 4976 97 65 49 49 49 4913 76 97 65 65 65 6527 27 76 97 76 76 7649 49 49 76 97 97 97 */function bubble_sort (\$ array) {\$ count = count (\$ array); if (\$ count <= 0) return false; for (\$ I = 0; \$ I <\$ count; \$ I ++) {for (\$ j = \$ count-1; \$ j> \$ I; \$ j --) {if (\$ array [\$ j] <\$ array [\$ J-1]) {\$ tmp = \$ array [\$ j]; \$ array [\$ j] = \$ arra Y [\$ J-1]; \$ array [\$ J-1] = \$ tmp ;}}return \$ array;}/* [Quick Sort (one-dimensional array)] [basic idea ]: in the current unordered zone R [1 .. h] Any data element is used as the benchmark for comparison (may be recorded as X). This benchmark is used to divide the current disordered zoning into two smaller disordered zones: R [1 .. i-1] and R [I 1 .. h], and the data elements in the unordered subarea on the left are smaller than or equal to the baseline element. The data elements in the unordered subarea on the right are greater than or equal to the reference element, the benchmark X is located at the final sorting position, that is, R [1 .. i-1] ≤ X. key ≤ R [I 1 .. h] (1 ≤ I ≤ H), when R [1 .. i-1] and R [I 1 .. h] when they are not empty, they are divided separately until all data elements in the unordered subarea are sorted. [Example ]: initial keyword [49 38 65 97 13 27 49] after the first exchange [27 38 65 97 76 13 49 49] after the second exchange [27 38 49 97 76 13 65 49] J left scan, position unchanged, after the third switch [27 38 13 97 76 49 65 49] I scan right, position unchanged, after the fourth Exchange [27 38 13 49 76 97 65 49] J left scan [27 38 13 49 76 97 65 49] (a division process) initial keyword [49 38 65 97 13 27 49] after a trip, [27 38 13] 49 [76 97 65 49] after a second trip,  27  49 [49 65] 76  13 27 38 49 49  76 97 final sorting result 13 27 38 49 49 65 76 97 status after sorting * /f Unction quick_sort (\$ array) {if (count (\$ array) <= 1) return \$ array; \$ key = \$ array ; \$ left_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 all the content of the array */function display_arr (\$ Array) {\$ len = count (\$ array); for (\$ I = 0; \$ I <\$ len; \$ I ++) {echo \$ array [\$ I]. '';} echo '<br/>';}/* Comparison and Selection of several sort algorithms 1. factors to consider when selecting the sorting method: (1) number of elements to be sorted n; (2) Size of the information of the elements themselves; (3) structure and distribution of keywords; (4) the condition of the language tool and the size of the auxiliary space. 2. Conclusion: (1) if n is small (n <= 50), you can directly insert or select sort. Because the movement of records required for direct insertion and sorting is more direct, it is better to directly select and sort records when the amount of information in the records is large. (2) If the initial state of the file has been basically ordered by the keyword, it is appropriate to select direct insertion or Bubble sorting. (3) If n is large, the time complexity is O (nlog2n. Quick sorting is currently the best method in comparison-based internal sorting. (4) In the comparative sorting method, after comparing the size of two keywords each time, only two possible transfer occurs. Therefore, a binary tree can be used to describe the comparison and determination process, it can be proved that when the n key words of the file are randomly distributed, any sort algorithm by means of "comparison" requires at least O (nlog2n) time. (5) When the record itself contains a large amount of information, you can use a linked list as the storage structure to avoid time-consuming moving records. * // * Sort test */\$ a = array ('12', '4', '16', '8', '13', '20 ', '5', '32'); echo 'the result of insert sort: '; \$ insert_a = insert_sort (\$ a); display_arr (\$ insert_a ); echo 'the result of select sort: '; \$ select_a = select_sort (\$ a); display_arr (\$ select_a); echo 'the result of bubble sort :'; \$ bubble_a = bubble_sort (\$ a); display_arr (\$ bubble_a); echo 'the result of bubble sort: '; \$ quick_a = quick_sort (\$ ); display_arr (\$ quick_a);?>
/* ** Arrange and combine * use the binary method to select a combination. For example, if you select 5 or 3, you only need to set 3 to 1, therefore, the resulting combination is 10 types of combinations, such as 01101 11100 00111 10011 01110 ** @ param: array to be arranged \$ arr * @ param minimum number \$ min_size * @ return: a new array that meets the conditions combination */function pl (\$ arr, \$ size = 5) {\$ len = count (\$ 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 & \$; 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); // traverses the 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 '));
```
Related Keywords:
Related Article

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.