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 {
let m = (i + j) / 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 binarySearch1(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) / 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 = binarySearch1(nums: nums, target: target)
print("目标元素 6 的索引 = \(index)")
}
}