We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent d18f593 commit 6cb8918Copy full SHA for 6cb8918
ruby/704-Binary-Search.rb
@@ -0,0 +1,33 @@
1
+# Iteraton
2
+def search(nums, target)
3
+ return -1 if nums.empty?
4
+
5
+ half = nums.length / 2
6
+ case nums[half] <=> target
7
+ when 1
8
+ search(nums[0...half], target)
9
+ when -1
10
+ idx = search(nums[half + 1..-1], target)
11
+ (idx == -1 ? -1 : half + 1 + idx)
12
+ when 0
13
+ half
14
+ end
15
+end
16
17
+# Recursion
18
19
+ left = 0
20
+ right = nums.length - 1
21
+ while left <= right
22
+ half = (left + right) / 2
23
24
25
+ right = half - 1
26
27
+ left = half + 1
28
29
+ return half
30
31
32
+ -1
33
0 commit comments