二分法查找数组是否包含某一元素,兼容正反序,代码实现:
代码如下:$searchValue = (int)$_GET['key'];
function search(array $array, $value)
{
$max = count($array)-1;
$min = 0;
$isAscSort = $array[$min]
while (TRUE) {
$sum = $min+$max;
$midKey = (int)($sum%2 == 1 ? ceil($sum/2) : $sum/2);
if ($max return -1;
} else if ($value == $array[$midKey]) {
return 1;
} else if ($value > $array[$midKey]) {
$isAscSort ? $min = $midKey+1 : $max = $midKey-1;
} else if ($value $isAscSort ? $max = $midKey-1 : $min = $midKey+1;
}
}
}
$array = array(
'4', '5', '7', '8', '9', '10', '11', '12'
);
// 正序
echo search($array, $searchValue);
// 逆序
rsort($array);
echo search($array, $searchValue);
这个之前搜过,看过百度百科的例子(Java的实现),还有一些其他技术宅写的Code,都有问题,根本就没实现,这些人不测试就放出来误导人,大家可以去搜搜看下,昨天闲来无事就自己写一个分享给大家。
这个没考虑非顺序键的数组,主要是方法,如果需要大家可以自己扩展下。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Dreamweaver Mac version
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.
