Last active
December 14, 2015 05:29
-
-
Save tuxido-feynman/5036131 to your computer and use it in GitHub Desktop.
Wouldn't it be great if you could get the first element of an array in O(logn) ? Well in Ruby you can with .index... but if you couldn't, here's what I'd do.
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
class Array | |
def first_index(x) | |
key = x | |
f = 0 | |
b = self.size | |
mid = get_mid(f,b) | |
until f == (b - 1) || f == b | |
self[mid] < key ? f = mid : b = mid | |
mid = get_mid(f,b) | |
end | |
if self[f] == key | |
f | |
elsif self[b] == key | |
b | |
else | |
nil | |
end | |
end | |
def get_mid(front,back) | |
middle = ((back - front) / 2) + front | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment