-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathMiddleSearch.php
More file actions
81 lines (70 loc) · 1.51 KB
/
MiddleSearch.php
File metadata and controls
81 lines (70 loc) · 1.51 KB
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
<?php
function pre($arr)
{
$data = func_get_args();
foreach($data as $key=>$val)
{
echo '<pre>';
print_r($val);
echo '</pre>';
}
}
function prend()
{
$data = func_get_args();
foreach($data as $key=>$val)
{
echo '<pre>';
print_r($val);
echo '</pre>';
}
exit();
}
/**
* 二分查找
* 基本思想是,在有序的数组里面递归折半查找
* @author yumancang
*
*/
class MiddleSearch
{
/**
* 整数数组
* @var array
*/
public $data = [];
public function __construct(Array $array)
{
$this->data = $array;
}
/**
* 二分查找
* 找到的话返回索引,否者返回-1
*
* @param int $val
* @param int $start
* @param int $end
* @return number|mixed|mixed|number
*/
public function search(int $val,int $start,int $end)
{
$middle = floor(($start + $end) / 2);
if ($val > $this->data[$middle]) {
return $this->search($val, $middle+1, $end);
}
if ($val < $this->data[$middle]) {
return $this->search($val, $start, $middle-1);
}
if ($val == $this->data[$middle]) {
return $middle;
}
return -1;
}
}
$start = memory_get_usage();
$bubble = new MiddleSearch([1,2,3,4,5,6,7,8,9,10,55]);
$result = $bubble->search(1,0,count($bubble->data)-1);
var_dump($result);
$end = memory_get_usage();
prend(($end-$start)/1024/1024);
?>