Skip to content

Instantly share code, notes, and snippets.

@tuxido-feynman
Last active December 14, 2015 05:29
Show Gist options
  • Save tuxido-feynman/5036131 to your computer and use it in GitHub Desktop.
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.
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