mirror of
https://github.com/krahets/hello-algo.git
synced 2026-08-20 23:41:00 +00: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