ihsandevs / php-binary-search
PHP 实现的二分查找算法
v1.0.0
2023-03-15 16:59 UTC
Requires
- php: >=7.2
Requires (Dev)
- phpunit/phpunit: ^10.0
README
关于
二分查找是一种在排序数组中查找目标值位置的搜索算法。二分查找将目标值与数组的中间元素进行比较。如果不相等,则消除目标值不可能存在的半边,并在剩余的半边继续搜索,再次取中间元素与目标值比较,重复此过程直到找到目标值。如果搜索结束时剩余的半边为空,则目标值不在数组中。
安装
composer require ihsandevs/php-binary-search
用法
- 使用默认比较函数进行搜索
<?php require_once __DIR__ . '/vendor/autoload.php'; use IhsanDevs\PhpBinarySearch\BinarySearch; // Create an instance of BinarySearch $binarySearch = new BinarySearch(); // Set the data and target $binarySearch->data = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]; $binarySearch->target = 60; // Perform the search with the default comparison function $binarySearch->search(); // Print the result $binarySearch->printResult(); // Output: Target 60 found at index 5 with 0 iteration(s) in 0 second(s) with memory usage 0 byte(s).
- 使用自定义比较函数进行搜索
<?php require_once __DIR__ . '/vendor/autoload.php'; use IhsanDevs\PhpBinarySearch\BinarySearch; $binarySearch = new BinarySearch(); // Create an instance of BinarySearch $binarySearch = new BinarySearch(); // Set the data and target $binarySearch->data = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]; $binarySearch->target = 60; // Define a custom comparison function $customCompareFn = function ($data, $target) { if ($data == $target) { return 0; } return ($data > $target) ? 1 : -1; }; // Perform the search with the custom comparison function $binarySearch->search($customCompareFn); // Print the result $binarySearch->printResult(); // Output: Target 60 found at index 5 with 0 iteration(s) in 0 second(s) with memory usage 0 byte(s).
如果您想查看带有日志的结果,可以使用 printLog()
方法。
<?php ... // Print the result with log $binarySearch->printResult()->printLog();
您还可以使用 printDebug()
方法以调试模式打印结果。
<?php ... // Print the result with debug $binarySearch->printResult()->printDebug();
测试
composer test
许可证
MIT 许可证 (MIT)。请参阅 许可证文件 获取更多信息。