mirror of
https://github.com/krahets/hello-algo.git
synced 2024-12-25 14:56:28 +08:00
7359a7cb4b
* feat(swift): review for chapter_computational_complexity * feat(swift): review for chapter_data_structure * feat(swift): review for chapter_array_and_linkedlist * feat(swift): review for chapter_stack_and_queue * feat(swift): review for chapter_hashing * feat(swift): review for chapter_tree * feat(swift): add codes for heap article * feat(swift): review for chapter_heap * feat(swift): review for chapter_graph * feat(swift): review for chapter_searching * feat(swift): review for chapter_sorting * feat(swift): review for chapter_divide_and_conquer * feat(swift): review for chapter_backtracking * feat(swift): review for chapter_dynamic_programming * feat(swift): review for chapter_greedy * feat(swift): review for utils * feat(swift): update ci tool * feat(swift): trailing closure * feat(swift): array init * feat(swift): map index
44 lines
1.2 KiB
Swift
44 lines
1.2 KiB
Swift
/**
|
||
* File: binary_search_recur.swift
|
||
* Created Time: 2023-09-02
|
||
* Author: nuomi1 (nuomi1@qq.com)
|
||
*/
|
||
|
||
/* 二分查找:问题 f(i, j) */
|
||
func dfs(nums: [Int], target: Int, i: Int, j: Int) -> Int {
|
||
// 若区间为空,代表无目标元素,则返回 -1
|
||
if i > j {
|
||
return -1
|
||
}
|
||
// 计算中点索引 m
|
||
let m = (i + j) / 2
|
||
if nums[m] < target {
|
||
// 递归子问题 f(m+1, j)
|
||
return dfs(nums: nums, target: target, i: m + 1, j: j)
|
||
} else if nums[m] > target {
|
||
// 递归子问题 f(i, m-1)
|
||
return dfs(nums: nums, target: target, i: i, j: m - 1)
|
||
} else {
|
||
// 找到目标元素,返回其索引
|
||
return m
|
||
}
|
||
}
|
||
|
||
/* 二分查找 */
|
||
func binarySearch(nums: [Int], target: Int) -> Int {
|
||
// 求解问题 f(0, n-1)
|
||
dfs(nums: nums, target: target, i: nums.startIndex, j: nums.endIndex - 1)
|
||
}
|
||
|
||
@main
|
||
enum BinarySearchRecur {
|
||
/* Driver Code */
|
||
static func main() {
|
||
let target = 6
|
||
let nums = [1, 3, 6, 8, 12, 15, 23, 26, 31, 35]
|
||
|
||
// 二分查找(双闭区间)
|
||
let index = binarySearch(nums: nums, target: target)
|
||
print("目标元素 6 的索引 = \(index)")
|
||
}
|
||
}
|