PHP algorithms and recursion

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<?php 
header("Content-Type:text/html;charset=utf-8");

$arr=array(1,12,53,14,5,16,7,18,91,10,11,120); //**Bubble sort** small numbers move to the front, large numbers move to the back

function getpao($arr) {

$len=count($arr); //set up an empty array to receive the bubbles that come up //this loop layer controls how many rounds of bubbling are needed

for($i=1;$i<$len;$i++) { //this loop layer controls how many comparisons are needed for one number to bubble up each round

for($k=0;$k<$len-$i;$k++) {

if($arr\[$k\]>$arr\[$k+1\]) {

$tmp=$arr\[$k+1\]; $arr\[$k+1\]=$arr\[$k\]; $arr\[$k\]=$tmp;

}

}

}

return $arr;

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
//**Selection sort** 

/\* On each pass, select the smallest (or largest) element from the data elements still to be sorted, and place it in order at the end of the already sorted sequence, until all the data elements to be sorted have been processed. Selection sort is an unstable sorting method */

function select_sort($arr){

for($i=0,$len=count($arr);$i<$len-1;$i++){ //assume the position of the minimum value $p=$i; //which elements are compared with now, the elements after $i

for($j=$i+1;$j<$len;$j++){

if($arr\[$p\]>$arr\[$j\]){ //a smaller one was found in the comparison, record the position of the minimum, and on the next comparison

$p=$j;
}
} //the position of the minimum is now determined, saved in $p

if($p != $i){
$tmp=$arr\[$p\]; $arr\[$p\]=$arr\[$i\]; $arr\[$i\]=$tmp;
}
}

return $arr;
}

//**Insertion sort**

/\* Start with the first element, which can be considered already sorted. Take the next element and scan backwards through the sequence of already sorted elements. If that (sorted) element is greater than the new element, move it to the next position. Repeat step 3 until you find a position where the sorted element is less than or equal to the new element. Insert the new element into the next position. */

function insert_sort($arr) {
//tell apart which part is already sorted
//and which part is not sorted
//find one element that needs to be sorted
//this element is the one that needs sorting, starting from the second element and going to the last element
//a loop can mark it out
//the i loop controls the element that needs to be inserted each time; once the element to insert is under control,
//the array has indirectly been split into 2 parts: the ones with an index less than the current one (on the left) are the sorted sequence

for($i=1, $len=count($arr); $i<$len; $i++) { //get the value of the element that currently needs to be compared.
$tmp = $arr\[$i\];
//the inner loop controls the comparison and the insertion
for($j=$i-1;$j>=0;$j--) { //$arr\[$i\];//the element to be inserted; $arr\[$j\];//the element to compare with
if($tmp < $arr\[$j\]) { //the element to insert turns out to be smaller, so swap positions //swap the element at the back with the element in front
$arr\[$j+1\] = $arr\[$j\]; //set the earlier number to the number that currently needs to be swapped
$arr\[$j\] = $tmp; } else { //if we hit an element that doesn't need to move //since the array is already sorted, there is no need to compare the earlier part again.
break;
}
}
} //insert this element into the already sorted sequence.
//return
return $arr;
}


//**Quicksort** an improvement on bubble sort
/\* Split the data to be sorted into two independent parts with one pass of sorting, where all the data in one part is smaller than all the data in the other part, then quicksort those two parts separately in the same way. The whole sorting process can be done recursively, which makes the entire data set an ordered sequence */

function quick\_sort($arr) { //first check whether we need to continue

$length = count($arr); if($length <= 1) {
return $arr;

} //if nothing was returned, there is more than 1 element in the array and sorting is required //choose a pivot //choose the first element

$base\_num = $arr\[0\]; //traverse all elements except the pivot, and put them into two arrays according to their relative size //initialize two arrays $left\_array = array();//smaller than the pivot
$right\_array = array();//greater than the pivot
for($i=1; $i<$length; $i++) {
if($base\_num > $arr\[$i\]) { //put into the left array
$left\_array\[\] = $arr\[$i\]; } else { //put into the right array
$right\_array\[\] = $arr\[$i\];
}
}
//then apply the same sorting process to the left and the right array respectively //call this function recursively and record the result
$left\_array = quick\_sort($left\_array);
$right\_array = quick\_sort($right\_array); //merge left, pivot, right
return array\_merge($left\_array, array($base\_num), $right\_array);
}
print\_r($arr);
echo "<br />冒泡";
print\_r(array\_reverse($arr));
echo "<br />冒泡排序";
rint\_r(getpao($arr));
echo "<br />选择排序";
print\_r(select\_sort($arr));
echo "<br />插入排序";
print\_r(insert\_sort($arr));
echo "<br />快速排序";
print\_r(quick_sort($arr));
echo "<br />"; // **Recursion** a function calls itself, but there must be a conditional check before it calls itself, otherwise it keeps calling forever function test($a=0,&$result=array()){ // global $result; $a++;
if($a<10){
$result\[\]=$a; test($a,$result);
}
return $result;
}

print_r(test());
echo "<br />";

//**Recursion using a global variable**

function test($a=0,$result=array()){
global $result; $a++; if ($a<10) {
$result\[\]=$a; test($a,$result);
} return $result; }

//**Recursion using a static variable** the variable that acts as the "bridge" between recursive calls is initialized with static, and each recursion keeps the value of the "bridge variable".

function test($a=0){
static $result=array(); $a++;
if ($a<10) {
$result\[\]=$a; test($a);
}
return $result;
}

//**Recursion: unlimited levels of categories**

$area = array(
array('id'=>1,'area'=>'北京','pid'=>0),
array('id'=>2,'area'=>'广西','pid'=>0),
array('id'=>3,'area'=>'广东','pid'=>0),
array('id'=>4,'area'=>'福建','pid'=>0),
array('id'=>11,'area'=>'朝阳区','pid'=>1),
array('id'=>12,'area'=>'海淀区','pid'=>1),
array('id'=>21,'area'=>'南宁市','pid'=>2),
array('id'=>45,'area'=>'福州市','pid'=>4),
array('id'=>113,'area'=>'亚运村','pid'=>11),
array('id'=>115,'area'=>'奥运村','pid'=>11),
array('id'=>234,'area'=>'武鸣县','pid'=>21) );

function t($arr,$pid=0,$lev=0){
static $list=array();
foreach ($arr as $v){
if($v\['pid'\]==$pid){
echo str\_repeat("",$lev).$v\['area'\]."<br />";
$list\[\]=$v; t($arr,$v\['id'\],$lev+1);
}
}
return $list;
}
$list=t($area);
print\_r($area);
echo "<br />";
print_r($list); ?>