This commit is contained in:
krahets
2024-05-15 19:00:27 +08:00
parent bd54cd096b
commit e434a3343c
36 changed files with 402 additions and 107 deletions
@@ -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"