class Test implements IteratorAggregate, Countable { protected $__data = []; function __construct(array $__data = []) { reset($__data); foreach($__data as $v) $this->__data[] = $v; } function binarySearch($__int32, $__index = NULL, $__length = NULL) { NULL !== $__index ?: $__index = 0x00; NULL !== $__length ?: $__length = $this->count() - $__index; if($__index + $__length > $this->count()) { var_dump('out of range'); return FALSE; } $t = $this->__data; $l = $__index; $r = $__index + $__length - 1; echo __FUNCTION__.":$__int32 from index:$l to index:$r"; do { $mid = intval(($l + $r + ($r % 0x02))/0x02); //$mid = intval(($r+$l)/0x02); if($t[$mid] === $__int32) { echo " | found $__int32@index $mid"; return intval(floor($mid)); } else if($t[$mid] > $__int32) { echo " | mid:$mid@ $t[$mid]>$__int32"; $r = $mid - 0x01; } else if($t[$mid] < $__int32) { echo " | mid:$mid@ $t[$mid]<$__int32"; $l = $mid + 0x01; } } while($l <= $r && $mid >= 0x00); return FALSE; } } $B = new Test(range(0,9)); foreach($B as $v) { $r = $B->binarySearch($v, 0, 10); $t = getType($r); if($r === false) $r = PHP_EOL."\tfalse"; print ' | ('.$t.') '; print $r.PHP_EOL; } var_dump($B); binarySearch:0 from index:0 to index:9 | mid:5@ 5>0 | mid:2@ 2>0 | mid:1@ 1>0 | found 0@index 0 | (integer) 0 binarySearch:1 from index:0 to index:9 | mid:5@ 5>1 | mid:2@ 2>1 | found 1@index 1 | (integer) 1 binarySearch:2 from index:0 to index:9 | mid:5@ 5>2 | found 2@index 2 | (integer) 2 binarySearch:3 from index:0 to index:9 | mid:5@ 5>3 | mid:2@ 2<3 | found 3@index 3 | (integer) 3 binarySearch:4 from index:0 to index:9 | mid:5@ 5>4 | mid:2@ 2<4 | mid:3@ 3<4 | found 4@index 4 | (integer) 4 binarySearch:5 from index:0 to index:9 | found 5@index 5 | (integer) 5 binarySearch:6 from index:0 to index:9 | mid:5@ 5<6 | mid:8@ 8>6 | mid:7@ 7>6 | found 6@index 6 | (integer) 6 binarySearch:7 from index:0 to index:9 | mid:5@ 5<7 | mid:8@ 8>7 | found 7@index 7 | (integer) 7 binarySearch:8 from index:0 to index:9 | mid:5@ 5<8 | found 8@index 8 | (integer) 8 binarySearch:9 from index:0 to index:9 | mid:5@ 5<9 | mid:8@ 8<9 | found 9@index 9 | (integer) 9 object(ILLI\Core\Std\ArrayList)#2 (1) { ["__data":protected]=> array(10) { [0]=> int(0) [1]=> int(1) [2]=> int(2) [3]=> int(3) [4]=> int(4) [5]=> int(5) [6]=> int(6) [7]=> int(7) [8]=> int(8) [9]=> int(9) } }