Last active
December 15, 2015 13:39
-
-
Save bluetwin/5268722 to your computer and use it in GitHub Desktop.
Suffix Array implementation in Ruby
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
# 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