FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
algorithm-php/src/Query/QuickQuery.php at master · m9rco/algorithm-php · GitHub
m9rco
/
algorithm-php
Public
Notifications
You must be signed in to change notification settings
Fork
484
Star
1.4k
Code
Issues
8
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
algorithm-php
/
src
/
Query
/
QuickQuery.php
Copy path
More file actions
More file actions
Latest commit
History
History
History
46 lines (43 loc) · 1.16 KB
Breadcrumbs
algorithm-php
/
src
/
Query
/
QuickQuery.php
Copy path
File metadata and controls
46 lines (43 loc) · 1.16 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
<?php
/**
* 快速查询
*
* @author Pu ShaoWei <pushaowei0727@gmail.com>
* @date 2017/8/23
* @license MIT
* -------------------------------------------------------------
* 思路分析:数组中间的值floor((low+top)/2)
* -------------------------------------------------------------
* 重复第二步操作直至找出目标数字
*/
/**
* QuickQuery
*
* @param $array
* @param $k
* @param int $low
* @param int $high
* @return int
*/
function
QuickQuery
(
$
array
,
$
k
,
$
low
=
0
,
$
high
=
0
)
{
//判断是否为第一次调用
if
(
count
(
$
array
) !=
0
and
$
high
==
0
) {
$
high
=
count
(
$
array
);
}
//如果还存在剩余的数组元素
if
(
$
low
<=
$
high
) {
//取$low和$high的中间值
$
mid
=
intval
((
$
low
+
$
high
) /
2
);
//如果找到则返回
if
(
$
array
[
$
mid
] ==
$
k
) {
return
$
mid
;
}
else
if
(
$
k
<
$
array
[
$
mid
]) {
//如果没有找到,则继续查找
return
QuickQuery
(
$
array
,
$
k
,
$
low
,
$
mid
-
1
);
}
else
{
return
QuickQuery
(
$
array
,
$
k
,
$
mid
+
1
,
$
high
);
}
}
return
-
1
;
}
echo
QuickQuery
([
4
,
5
,
7
,
8
,
9
,
10
,
8
],
8
);
Back
|
FazBrowse Home
|
New Git URL