mirror of
https://github.com/krahets/hello-algo.git
synced 2026-04-24 18:43:59 +08:00
build
This commit is contained in:
@@ -422,9 +422,32 @@ comments: true
|
||||
=== "Ruby"
|
||||
|
||||
```ruby title="binary_search_recur.rb"
|
||||
[class]{}-[func]{dfs}
|
||||
### 二分查找:问题 f(i, j) ###
|
||||
def dfs(nums, target, i, j)
|
||||
# 若区间为空,代表无目标元素,则返回 -1
|
||||
return -1 if i > j
|
||||
|
||||
# 计算中点索引 m
|
||||
m = (i + j) / 2
|
||||
|
||||
[class]{}-[func]{binary_search}
|
||||
if nums[m] < target
|
||||
# 递归子问题 f(m+1, j)
|
||||
return dfs(nums, target, m + 1, j)
|
||||
elsif nums[m] > target
|
||||
# 递归子问题 f(i, m-1)
|
||||
return dfs(nums, target, i, m - 1)
|
||||
else
|
||||
# 找到目标元素,返回其索引
|
||||
return m
|
||||
end
|
||||
end
|
||||
|
||||
### 二分查找 ###
|
||||
def binary_search(nums, target)
|
||||
n = nums.length
|
||||
# 求解问题 f(0, n-1)
|
||||
dfs(nums, target, 0, n - 1)
|
||||
end
|
||||
```
|
||||
|
||||
=== "Zig"
|
||||
|
||||
Reference in New Issue
Block a user