Skip to content

Commit

Permalink
704
Browse files Browse the repository at this point in the history
  • Loading branch information
TedTran2019 committed Jul 7, 2022
1 parent d18f593 commit 6cb8918
Showing 1 changed file with 33 additions and 0 deletions.
33 changes: 33 additions & 0 deletions ruby/704-Binary-Search.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# Iteraton
def search(nums, target)
return -1 if nums.empty?

half = nums.length / 2
case nums[half] <=> target
when 1
search(nums[0...half], target)
when -1
idx = search(nums[half + 1..-1], target)
(idx == -1 ? -1 : half + 1 + idx)
when 0
half
end
end

# Recursion
def search(nums, target)
left = 0
right = nums.length - 1
while left <= right
half = (left + right) / 2
case nums[half] <=> target
when 1
right = half - 1
when -1
left = half + 1
when 0
return half
end
end
-1
end

0 comments on commit 6cb8918

Please sign in to comment.