3v4l.org

run code in 300+ PHP versions simultaneously
<?php function BinSearch($needle, $haystack){ asort($haystack); $max = count($haystack); $min = $pos = 0; $mid = false; do { printf("\n\nSeeking for %d, found %d between %d and %d…", $needle, $haystack[$pos], $min, $max); if ( $needle === $haystack[$pos] ) { return $pos; } if ( $haystack[$pos] > $needle ) { $max = $pos; // we don't need to go any higher than $pos $pos = (int)max($min, $pos/2); printf("we're too high, coming down to %d", $pos); } else { $min = $pos; $pos = (int)min($max, $pos+($max - $pos) / 2); printf("we're too low, increasing to %d", $pos); } } while (($pos < $max) && ($haystack[$pos] !== $needle)); return $pos; } $x = range(0,999); $foundPosition = BinSearch($seek = 82,$x); echo "\n\n\nFound $seek at position $foundPosition.";

preferences:
58.69 ms | 402 KiB | 5 Q