Skip to content

Commit 507f1af

Browse files
committed
feat: new arithmetic 🎨
1 parent ee25d43 commit 507f1af

File tree

2 files changed

+49
-8
lines changed

2 files changed

+49
-8
lines changed

package/Query/InseertQuery.php

Lines changed: 0 additions & 8 deletions
This file was deleted.

package/Query/InsertQuery.php

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
<?php
2+
/**
3+
* insertQuery
4+
*
5+
* @author Pu ShaoWei <[email protected]>
6+
* @date 2017/8/25
7+
* @license Mozilla
8+
* -------------------------------------------------------------
9+
* 思路分析:对于数组长度比较大,关键字分布又是比较均匀的来说,插值查找的效率比折半查找的效率高
10+
* -------------------------------------------------------------
11+
* 它是二分查找的改进。
12+
* 在英文词典里查找“apple”,你下意识里翻开词典是翻前面的书页还是后面的书页呢?如果再查“zoo”,你又会怎么查?
13+
* 显然你不会从词典中间开始查起,而是有一定目的地往前或往后翻。
14+
*
15+
* @param $container
16+
* @param $num
17+
* @return int
18+
*/
19+
function insertQuery(array $container, $num)
20+
{
21+
$count = count($container);
22+
$lower = 0;
23+
$high = $count - 1;
24+
25+
while ($lower <= $high) {
26+
if ($container[ $lower ] == $num) {
27+
return $lower;
28+
}
29+
if ($container[ $high ] == $num) {
30+
return $high;
31+
}
32+
33+
$left = intval($lower + $num - $container[ $lower ]);
34+
$right = ($container[ $high ] - $container[ $lower ]) * ($high - $lower);
35+
36+
$middle = $left /$right;
37+
38+
if ($num < $container[ $middle ]) {
39+
$high = $middle - 1;
40+
} else if ($num > $container[ $middle ]) {
41+
$lower = $middle + 1;
42+
} else {
43+
return $middle;
44+
}
45+
}
46+
return false;
47+
}
48+
49+
echo insertQuery([4, 5, 7, 8, 9, 10, 8], 8);

0 commit comments

Comments
 (0)