PHP Classic algorithm

Source: Internet
Author: User

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.

<?php
for ($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, and 6 lines are written.
for ($i =0; $i <6; $i + +) {
$a [$i][0]=1;
$a [$i] [$i]=1;
}
The values of the first and last digits are saved 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 you want to insert is already the largest, print directly
if ($arr [$n-1] < $in) {
$arr [$n +1] = $in; Print_r ($arr);
}
for ($i =0; $i < $n; $i + +) {
Find the location to insert
if ($arr [$i] >= $in) {
$t 1= $arr [$i];
$arr [$i] = $in;
Move the back of 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. 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.

<?php
function Q ($array) {
if (count ($array) <= 1) {return $array;}
$key, divided into two sub-arrays
$key = $array [0];
$l = Array ();
$r = Array ();
Recursively sort each other, 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. 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.

<?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 (' Don't have ... ');
}
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.

<?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: 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)

<?php
function 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;
}
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 ($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> ';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 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 >= $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 ' function Quicksort ($array)
{
$n = count ($array);
if ($n <= 1)
{
return $array;
}
$key = $array [' 0 '];
$array _r = Array ();
$array _l = Array ();
for ($i = 1; $i < $n; $i + +)
{
if ($array [$i] > $key)
{
$array _r[] = $array [$i];
}
Else
{
$array _l[] = $array [$i];
}
}
$array _r = quicksort ($array _r);
$array _l = quicksort ($array _l);
$array = Array_merge ($array _l, Array ($key), $array _r);
return $array;
}
Print_r (Quicksort ($array));
Echo ' function Insertsort ($array)
{
$n = count ($array);
for ($i = 1; $i < $n; $i + +)//[0,i-1] [I,n]
{
$j = $i-1;
$temp = $array [$i];
while ($array [$j] > $temp)
{
$array [$j + 1] = $array [$j];
$array [$j] = $temp;
$j--;
}
}
return $array;
}
Print_r (Insertsort ($array));
?>

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

<?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 sorted sequence, the sequence remains orderly until all the data elements are sorted are inserted.
"Example":
[Initial key Words] [49] 38 65 97 76 13 27 49
j=2 (38) [38 49] 65 97 76 13 27 49
J=3 (65) [38 49 65] 97 76 13 27 49
J=4 (97) [38 49 65 97] 76 13 27 49
J=5 (76) [38 49 65 76 97] 13 27 49
J=6 (13) [13 38 49 65 76 97] 27 49
J=7 (27) [13 27 38 49 65 76 97] 49
J=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": 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 finished.
"Example":
[Initial key Words] [49 38 65 97 76 13 27 49]
First trip sorted after 13 [38 65 97 76 49 27 49]
Second trip sorted after 13 27 [65 97 76 49 38 49]
Third trip sort after 13 27 38 [97 76 49 65 49]
Four-trip sort after 13 27 38 49 [49 97 65 76]
Five-trip sort after 13 27 38 49 49 [97 97 76]
Six-trip sort after 13 27 38 49 49 76 [76 97]
Seventh trip sort after 13 27 38 49 49 76 76 [97]
Last sorted results 13 27 38 49 49 76 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": 22 Compare the size of the data element 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 light bubbles can not under the principle of heavy bubbles,
Scan the array r from the bottom up, where the light bubbles that violate this principle are scanned so that they "float" upward, so repeatedly, until the last two bubbles are light and heavy.
"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 49 49
13 76 97 65 65 65 65 65
27 27 76 97 76 76 76 76
49 49 49 76 97 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] = $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 "benchmark" for comparison (may be remembered as X),
Use 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 unordered sub-region is less than or equal to the datum element.
The data elements in the unordered sub-region on the right are greater than or equal to the datum element, and 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 non-empty, they are divided into the above partitioning 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 [27 38 49 97 76 13 65 49]
J left scan, position unchanged, after third Exchange [27 38 13 97 76 49 65 49]
I scan right, position unchanged, after fourth Exchange [27 38 13 49 76 97 65 49]
J Left Scan [27 38 13 49 76 97 65 49]
(One-time partitioning process)
initial keyword [49 38 65 97 76 13 27 49]
After a trip sort [27 38 13] 49 [76 97 65 49]
Two times sorted [13] 27 [38] 49 [49 65]76 [97]
Three trips sorted after 13 27 38 49 49 [65]76 97
Final sorted results 13 27 38 49 49 65 76 97
Status after the order of each trip
*/
function Quick_sort ($array) {
if (count ($array) <= 1) return $array;
$key = $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 the entire contents 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 sorting algorithms
1. Select the factors to consider for the sorting method:
(1) Number of elements to be sorted n;
(2) The size of the information of the element itself;
(3) The structure and distribution of the keywords;
(4) The condition of the language tool, the size of the auxiliary space, etc.
2. Summary:
(1) If n is smaller (n <= 50), it can be either directly inserted or sorted directly. 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 (' 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 ($a);
Display_arr ($quick _a);
?>

/**
* Arrangement Combination
* Using the binary method for the combination of choice, such as 5 select 3 o'clock, only 3 bits is 1 can be, so the available combination is 01101 11100 00111 10011 01110 and other 10 combinations
*
* @param arrays that need to be arranged $arr
* @param minimum number $min _size
* @return new array combinations that meet the criteria
*/
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 '));

PHP Classic algorithm

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.