Last active
August 29, 2015 14:17
-
-
Save sheldonh/28f333686979b4ff8d63 to your computer and use it in GitHub Desktop.
Binary search worst case
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
binsearch = (a, t, probe) -> | |
min = 0 | |
max = a.length - 1 | |
while (min <= max) | |
i = Math.floor((min + max) / 2) | |
v = a[i] | |
probe? i, v | |
if v is t | |
return i | |
else if v < t | |
min = i + 1 | |
else | |
max = i - 1 | |
return -1 | |
review = (n, probe) -> | |
a = mka(n) | |
theoC = Math.ceil(Math.log2(a.length + 1)) | |
worstC = 0 | |
for v in a | |
do (v) -> | |
c = 0 | |
i = binsearch(a, v, -> c++) | |
worstC = Math.max(c, worstC) | |
probe? theoC, worstC | |
if worstC isnt theoC | |
console.log "Theoretical worst case #{theoC} disagrees with imperative worst case #{worstC} for n #{n}" | |
mka = (n) -> | |
a = [] | |
if n > 0 | |
a.push(i) for i in [1..n] | |
a | |
review(n) for n in [0..1024] | |
# The two answers that Khan Academy got wrong: | |
review(n, (theoC, worstC) -> console.log n, theoC, worstC) for n in [193, 1580000] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment