hello-algo/codes/swift/chapter_searching/binary_search.swift
Yudong Jin e720aa2d24
feat: Revised the book (#978)
* Sync recent changes to the revised Word.

* Revised the preface chapter

* Revised the introduction chapter

* Revised the computation complexity chapter

* Revised the chapter data structure

* Revised the chapter array and linked list

* Revised the chapter stack and queue

* Revised the chapter hashing

* Revised the chapter tree

* Revised the chapter heap

* Revised the chapter graph

* Revised the chapter searching

* Reivised the sorting chapter

* Revised the divide and conquer chapter

* Revised the chapter backtacking

* Revised the DP chapter

* Revised the greedy chapter

* Revised the appendix chapter

* Revised the preface chapter doubly

* Revised the figures
2023-12-02 06:21:34 +08:00

62 lines
2 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* 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, 26, 31, 35]
/* */
var index = binarySearch(nums: nums, target: target)
print("目标元素 6 的索引 = \(index)")
/* */
index = binarySearchLCRO(nums: nums, target: target)
print("目标元素 6 的索引 = \(index)")
}
}