8000 Merge pull request #29 from anantcodes/master · TheAlgorithms/Swift@76f79d9 · GitHub
[go: up one dir, main page]

Skip to content

Commit 76f79d9

Browse files
authored
Merge pull request #29 from anantcodes/master
Binary search algorithm added
2 parents e369d22 + c26af2f commit 76f79d9

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

Search/BinarySearch.swift

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
import Foundation
2+
3+
public func binarySearch<T: Comparable>(_ a: [T], key: T) -> Int? {
4+
var lowerBound = 0
5+
var upperBound = a.count
6+
while lowerBound < upperBound {
7+
let midIndex = lowerBound + (upperBound - lowerBound) / 2
8+
if a[midIndex] == key {
9+
return midIndex
10+
} else if a[midIndex] < key {
11+
lowerBound = midIndex + 1
12+
} else {
13+
upperBound = midIndex
14+
}
15+
}
16+
return nil
17+
}
18+
// The code below can be used for testing
19+
20+
// var numbers = [7, 10, 13, 17, 19, 24, 29, 31, 32, 37, 41, 43, 47, 51, 53, 119, 163, 611, 627]
21+
// if let searchIndex = binarySearch(numbers, key: 10) {
22+
// print("Element found on index: \(searchIndex)")
23+
// }
24+
// else {
25+
// print("Element not found")
26+
// }
27+

0 commit comments

Comments
 (0)
0