PHP Classic Algorithm Collection "Classic Collection" _php tips

Source: Internet
Author: User
Tags arrays benchmark php code php programming php regular expression pow

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

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

Train of thought: how many lines for once, then in the inside space and asterisk for once.

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

2, bubble Sort, C basic algorithm, from small to large on a group of numbers sorted.

Train of thought: This problem from small to large, the first round row smallest, second round row 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]) {//Small to large
      $p = $ arr[$i];
      $arr [$i] = $arr [$j];
      $arr [$j]= $p;
    }
}} Var_dump ($arr);

3, Yang Hui's triangle, write in PHP.

Idea: The first and last of each row is 1, no change, the middle is the front row with the left row of the and, this algorithm is a two-dimensional array to save, another algorithm with a one-dimensional array can also be implemented, a row of output, interested to write 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 are 1, and 6 lines are written for
 ($i =0; $i <6; $i + +) {
  $a [$i][0]=1;
  $a [$i] [$i]=1;
 }
Out of 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, the need to insert a number, in its original order to insert, maintain the original sorting method.

Idea: Find the position that you want to insert a large number of, replace it, and then move the number back one after the other.

<?php
$in = 2;
$arr = Array (1,1,1,3,5,7);
$n = count ($arr);
If the number you want to insert is already the largest, print the
if ($arr [$n-1] < $in) {
  $arr [$n +1] = $in; Print_r ($arr);
  }
for ($i =0; $i < $n; $i + +) {
//Find the position to insert
  if ($arr [$i] >= $in) {
    $t 1= $arr [$i];
    $arr [$i] = $in;
Move the 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. Sorting a group of numbers (fast sorting algorithm).

Train of thought: divide a trip into two parts, then recursively sort the two parts, and finally merge.

<?php
function 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, 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,44,3,4,33);
Print_r (q ($arr));

6, in an array to find the elements you need (binary lookup algorithm).

Train of thought: A value in an array is bounded and then recursively searched until the end.

<?php
function 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, the combination of multiple arrays, do not array_merge (), the topic to the Forum.

Idea: Iterate through each array and make a new array again.

<?php
function 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;
}
Test
Print_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, the year of the Ox cattle: There is a cow, to 4 years old to be fertile, one at a, born are the same cow, to 15 years old sterilization, no longer able to live, 20-year-old death, ask how many cows after n years. (From forum)

<?php
function T ($n) {
    static $num = 1 for
    ($j =1; $j <= $n; $j + +) {
        if ($j >=4 && $j < {$num ++;t ($n-$j);}
        if ($j ==20) {$num--;}
     }
     return $num;
}
Test
Echo T (8);

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

Bubble sort (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> ';
}

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);
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> ';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);
Dump ($data);
Shellsort ($data, $nums);
Dump ($data);
Function Shellsort (& $arr, $n)
{for
($increment = Intval ($n/2); $increment > 0; $increment = intval ($incre MENT/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-$i Ncrement];
   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);
Dump ($data);
Quicks ($data, 0,count ($data)-1);
Dump ($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];
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 sort: 22 Exchange values, the smallest value on the leftmost, as the lightest bubble at the top. Swap 22 for an entire column, the smallest number is at the far left, each time a minimum number in the remaining number, the number of "taking" is composed of an ordered interval, the remaining values constitute a disordered interval, and each element value in the ordered interval is smaller than the disordered interval.

Quick sort: Base number, left and right two arrays, recursive invocation, merging.

Insertion sort: The sorting interval is divided into two parts, the left is ordered, the right is unordered, the first element from the right interval is inserted into the left interval, if this element is larger than the rightmost element on the left, it stays where it is, if the element is smaller than the rightmost element on the left, it is inserted at the far right of the rightmost element, while the rightmost element moves to the right one, and the calculator minus one , re-compare the preceding element until the preceding element is smaller than the element you want to insert, repeating the steps above.

Note the processing of interval endpoint values, and the first element of the array is labeled 0.

<?php//php Common Sort 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 (3,6,1,5,9,0,4,6,11);
Print_r (Bubblesort ($array));
Echo '  

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

<?php/* "Insert sort (one-dimensional array)" "Basic idea": each time a sorted data element is inserted into the appropriate position in the previously sorted sequence, so that the sequence remains in order until all the data elements to be sorted are inserted.  "Example": [Initial keyword] [j=2] [97] [38 49] (J=3) [$] (+) [$] (+) [+] [+]
J=5 (a) [j=6] [27) [13 27 38 49 65 76 97] 49 (+) [A] [a] (+) [j=7] J=8 (a)/function Insert_sort ($arr) {$count = count ($arr); for ($i =1; $i < $count; $i + +) {$t
  MP = $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, and the order is placed at the end of the ordered sequence until all the data elements to be sorted are finished. "Example": [Initial keyword] [49 38 65 97 76 13 27 49] First sort after 13 [38 65 97 76 49 27 49] second sort after 13 27 [65 97 76 49 38 49] third trip after 13 27 3 8 [97 76 49 65 49] Fourth trip sort after 13 27 38 49 [49 97 65 76] Fifth trip sort after 13 27 38 49 [49 + 97] Sixth trip Sort 97 76 13 27 38 [49 49] Seventh Trip sort after 13 27 38 49 49 76 76 [97] The final sort result of a-Elect_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 comparing the size of the data element to be sorted, the order of two data elements is found to be exchanged until there is no inverse data element. Sort procedure: Imagine the array r[1 to be sorted ...
N] vertically erect, each data element as a bubble of weight, according to the principle that the light bubbles cannot be under the heavy bubbles, scan the array r from the bottom up and scan the light bubbles that violate this principle so that they "float" upwards, so that the last two bubbles are light, and the heavy is the next.  "Example": 49 13 13 13 13 13 13 13 38 49 27 27 27 27 27 27 65 38 49 38 38 38 38 38 97 65 38 49 49 49 49 49 76 97 65 49 49 49 A-A-i-bubble_sort ($array) {$count = Coun)--------
T ($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] = $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], is used as the "benchmark" for the comparison (may be recorded as x), use this benchmark to divide the current unordered division into about two smaller unordered areas: r[1..i-1] and R[i 1..H], and the data element in the left unordered child is less than or equal to the datum element. The data elements in the right unordered child are greater than or equal to the datum element, while Datum X is at the position of the final sort, 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] are not empty, the above partitioning process is performed on them respectively.
Until the data elements in all unordered subgroups are sorted. "Example": initial keywords [49 38 65 97 76 13 27 49] After the first Exchange [27 38 65 97 76 13 49 49] After the second exchange [I] J left-scan, position unchanged, after the third exchange [MB] I scan to the right, position unchanged, after the fourth Exchange [27 38 13 49 76 97 65 49] (one division process) Initial keyword [49 3] (the first time)  8 65 97 76 13 27 49] One trip after [27 38 13] 49 [76 97 65 49] Two trip sort [13] 27 [38] 49 [49 65]76 [97] Three trip sort 13 27 38 49 49 [65]76 97 Final Sort Results 13 27 38 49 49 65 76 97 Each sort of the status * * function Quick_sort ($array) {if (count ($array) <= 1) return $array; $k
EY = $array [0];
$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 array all content/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.
Select the factors to consider: (1) The number of elements to be sorted n; (2) The size of the element itself, (3) The structure and distribution of the keywords, (4) The conditions of the language tool, the size of the auxiliary space, etc. 2. Summary: (1) If n is small (n <= 50), you can use direct insertion sort or direct selection.
Because the record-moving operation required by direct insertion sort is more than direct selection order, it is better to use direct selection when the information of record itself is large.
(2) If the initial state of the file is in accordance with the basic order of the keyword, then the selection of direct insertion or bubble sort is appropriate. (3) If the n is large, then the time complexity of O (nlog2n) Sorting method should be used: 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) After each comparison of the size of two keywords in a comparison-based sort method, there are only two possible transitions, so a binary tree can be used to describe the comparison decision process, thus proving that when the N-keyword of a file is randomly distributed, any use of a "comparison" sorting algorithm requires at least O (nlog2n
) of the time.
(5) When the information of the record itself is large, in order to avoid consuming a lot of time to move records, you can use the linked list as the storage structure.
*//////* Sort Test $a = array (' 12 ', ' 4 ', ' 16 ', ' 8 ', ' 13 ', ' 20 ', ' 5 ', ' 32 ');
Echo ' 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 ($a);

 Display_arr ($quick _a);?>
/** * Permutation combination * Using the binary method of the combination of choice, such as 5 select 3 o'clock, only 3 bits to 1 on it, so the resulting combination is 01101 11100 00111 10011 01110, such as 10 combinations * * @param need to arrange the array $arr
 * @param minimum number of $min _size * @return new array combinations that satisfy the conditions/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 & $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 '));

More about PHP Interested readers can view the site topics: "PHP Data structure and algorithm tutorial", "PHP Programming Algorithm Summary", "PHP encryption Method Summary", "PHP code and transcoding Operation Skills Summary", "PHP object-oriented Programming Program", " PHP Mathematical Calculation Skills Summary, "PHP array Operation techniques Encyclopedia", "PHP string (String) Usage 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.