Skip to content

Instantly share code, notes, and snippets.

@bluetwin
Last active December 15, 2015 13:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bluetwin/5268722 to your computer and use it in GitHub Desktop.
Save bluetwin/5268722 to your computer and use it in GitHub Desktop.
Suffix Array implementation in Ruby
# Originally viewed on Giorgio Gonnella's blog
# http://looks-interesting.blogspot.com/2009/07/simple-implementation-of-suffix-array.html
# added substring and binary search
class SuffixArray
attr_reader :suf, :string
def initialize(string)
@string = string
@suf = (0..string.size-1).sort_by{|i|@string[i..-1]}
end
def suffix(idx)
@string[@suf[idx]..@string.size-1]
end
def bsearch(str)
low = 0
high = @suf.length-1
found = nil
while(low <= high) do
mid = (low + high) / 2
comp = suffix(mid)
if comp > str
high = mid - 1
elsif comp < str
low = mid + 1
else
found = comp
low = high + 1
end
end
found
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment