hello-algo/codes/swift/chapter_searching/binary_search.swift

63 lines
2 KiB
Swift
Raw Normal View History

/**
* File: binary_search.swift
* Created Time: 2023-01-28
* Author: nuomi1 (nuomi1@qq.com)
*/
/* */
func binarySearch(nums: [Int], target: Int) -> Int {
// [0, n-1] i, j
var i = 0
var j = nums.count - 1
// i > j
while i <= j {
2023-05-21 04:51:32 +08:00
let m = i + (j - i) / 2 // m
if nums[m] < target { // target [m+1, j]
i = m + 1
} else if nums[m] > target { // target [i, m-1]
j = m - 1
} else { //
return m
}
}
// -1
return -1
}
/* */
2023-05-18 20:27:58 +08:00
func binarySearchLCRO(nums: [Int], target: Int) -> Int {
// [0, n) i, j +1
var i = 0
var j = nums.count
// i = j
while i < j {
2023-05-21 04:51:32 +08:00
let m = i + (j - i) / 2 // m
if nums[m] < target { // target [m+1, j)
i = m + 1
} else if nums[m] > target { // target [i, m)
j = m
} else { //
return m
}
}
// -1
return -1
}
@main
enum BinarySearch {
/* Driver Code */
static func main() {
let target = 6
2023-05-21 19:29:24 +08:00
let nums = [1, 3, 6, 8, 12, 15, 23, 26, 31, 35]
/* */
var index = binarySearch(nums: nums, target: target)
print("目标元素 6 的索引 = \(index)")
/* */
2023-05-18 20:27:58 +08:00
index = binarySearchLCRO(nums: nums, target: target)
print("目标元素 6 的索引 = \(index)")
}
}