You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
hello-algo/codes/swift/chapter_searching/binary_search.swift

63 lines
2.0 KiB

/**
* 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 {
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
}
/* */
func binarySearchLCRO(nums: [Int], target: Int) -> Int {
// [0, n) i, j +1
var i = 0
var j = nums.count
// i = j
while i < j {
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
let nums = [1, 3, 6, 8, 12, 15, 23, 67, 70, 92]
/* */
var index = binarySearch(nums: nums, target: target)
print("目标元素 6 的索引 = \(index)")
/* */
index = binarySearchLCRO(nums: nums, target: target)
print("目标元素 6 的索引 = \(index)")
}
}