Skip to content

Instantly share code, notes, and snippets.

@shikachii
Last active November 27, 2016 17:36
Show Gist options
  • Save shikachii/0fe6c3e557c168f28c86d7c65095aafe to your computer and use it in GitHub Desktop.
Save shikachii/0fe6c3e557c168f28c86d7c65095aafe to your computer and use it in GitHub Desktop.
二分探索
class Array
def binarysearch(keyword)
return "Couldn't find the keyword." if self.size < 1
mid = self.size/2.to_i
pivot = self[mid]
puts self[mid]
binary = Array.new
if keyword == self[mid]
return "Found the number."
end
if keyword < self[mid]
(0..mid-1).each do |i|
binary.push(self[i])
end
else
(mid+1..self.size-1).each do |i|
binary.push(self[i])
end
end
binary = binary.binarysearch(keyword)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment