C++实现方式:
#include<iostream> #include<stdlib.h>
#include<algorithm> using namespace std; int Bisection(int key, int arr[], int low, int high) { if(low > high) return -1; int mid = (low + high) / 2; if(key < arr[mid]) return Bisection(key, arr, low, mid - 1); else if(key == arr[mid]) return mid; else return Bisection(key, arr, mid + 1, high); } // 写算法之前最好先写好测试用例 int main() { int n, key, position; cin>>n; int *arr; arr = (int*)calloc(n, sizeof(int)); for(int i = 0; i < n; i++) { cin>>arr[i]; }
// 对数组进行排序
sort(arr, arr + n); cin>>key; if((position = Bisection(key, arr, 0, n - 1)) != -1) { cout<<"关键字位置:"<<position<<endl; }else { cout<<"未找到关键字!"<<endl; } // 在使用动态数组时,最后要记得释放这些内存 free(arr); return 0; }
PHP实现方式:
<?php /** * 实现类 */ namespace achieve; class publicMethod { /** * @param $key * @param $arr * @param $low * @param $high * @return float|int * @description 二分查找的实现方法 */ public function Bisection($key, $arr, $low, $high) { if ($low > $high) return -1; $mid = round(($low + $high) / 2); if ($key < (int)$arr[$mid]) return $this->Bisection($key, $arr, $low, $mid - 1); else if($key == (int)$arr[$mid]) return $mid; else return $this->Bisection($key, $arr, $mid + 1, $high); } } /** * 测试类 */ namespace test; use achieve; class Test { /** * 测试二分查找的用例方法 */ public function testBisection() { $pm = new \achieve\publicMethod(); $n = fgets(STDIN); $arr = explode(" ", trim(fgets(STDIN))); $key = fgets(STDIN); sort($arr, SORT_REGULAR); if (($position = $pm->Bisection((int)$key, $arr, 0, count($arr) - 1)) != -1) { fwrite(STDOUT, "关键字位置是:$position"); }else { fwrite(STDOUT, "未找到关键字!"); } } } $test = new Test(); $test->testBisection(); ?>
这段PHP代码需要在命令行下执行,用php filepath.php来执行filepath是该脚本的完整路径加文件名。
在写具体的算法实现之前最好先将测试用例写好。