Skip to content

Instantly share code, notes, and snippets.

@BenLangmead
Last active December 24, 2015 07:39
Show Gist options
  • Save BenLangmead/6765264 to your computer and use it in GitHub Desktop.
Save BenLangmead/6765264 to your computer and use it in GitHub Desktop.
def binarySearchSA(t, sa, p):
assert t[-1] == '$' # t already has terminator
assert len(t) == len(sa) # sa is the suffix array for t
l, r = 0, len(sa) # invariant: sa[l] < p < sa[r]
if r == l+1: return r
while True:
c = (l + r) // 2
# determine whether p < T[sa[c]:] by doing comparisons
# starting from left-hand sides of p and T[sa[c]:]
plt = True # assume p < T[sa[c]:] until proven otherwise
i = 0
while i < len(p) and sa[c]+i < len(t):
if p[i] < t[sa[c]+i]:
break # p < T[sa[c]:]
elif p[i] > t[sa[c]+i]:
plt = False
break # p > T[sa[c]:]
i += 1 # tied so far
if plt:
if c == l + 1: return c
r = c
else:
if c == r - 1: return r
l = c
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment