3v4l.org

run code in 200+ 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.";
based on sn2mS
Output for 7.1.25 - 7.3.4
Seeking for 82, found 0 between 0 and 1000…we're too low, increasing to 500 Seeking for 82, found 500 between 0 and 1000…we're too high, coming down to 250 Seeking for 82, found 250 between 0 and 500…we're too high, coming down to 125 Seeking for 82, found 125 between 0 and 250…we're too high, coming down to 62 Seeking for 82, found 62 between 0 and 125…we're too low, increasing to 93 Seeking for 82, found 93 between 62 and 125…we're too high, coming down to 62 Seeking for 82, found 62 between 62 and 93…we're too low, increasing to 77 Seeking for 82, found 77 between 62 and 93…we're too low, increasing to 85 Seeking for 82, found 85 between 77 and 93…we're too high, coming down to 77 Seeking for 82, found 77 between 77 and 85…we're too low, increasing to 81 Seeking for 82, found 81 between 77 and 85…we're too low, increasing to 83 Seeking for 82, found 83 between 81 and 85…we're too high, coming down to 81 Seeking for 82, found 81 between 81 and 83…we're too low, increasing to 82 Found 82 at position 82.