Created
November 15, 2020 10:21
-
-
Save ceth-x86/28884be12f0af144aff7b9bfabfa788e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func Search(n int, f func(int) bool) int { | |
// Define f(-1) == false and f(n) == true. | |
// Invariant: f(i-1) == false, f(j) == true. | |
i, j := 0, n | |
for i < j { | |
h := i + (j-i)/2 // avoid overflow when computing h | |
// i ≤ h < j | |
if !f(h) { | |
i = h + 1 // preserves f(i-1) == false | |
} else { | |
j = h // preserves f(j) == true | |
} | |
} | |
// i == j, f(i-1) == false, and f(j) (= f(i)) == true => answer is i. | |
return i | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment