Skip to content

Commit 81a3b5b

Browse files
authored
Merge branch 'master' into FernandaOchoa-LinearSearch
2 parents 62719e9 + 8223059 commit 81a3b5b

2 files changed

Lines changed: 55 additions & 1 deletion

File tree

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
/**
2+
Binary Search
3+
4+
5+
Recursively splits the array in half until the value is found.
6+
7+
If there is more than one occurrence of the search key in the array, then
8+
there is no guarantee which one it finds.
9+
10+
Note: The array must be sorted!
11+
You can find the documentation on https://www.raywenderlich.com/139821/swift-algorithm-club-swift-binary-search-tree-data-structure]
12+
**/
13+
14+
import Foundation
15+
16+
// The recursive version of binary search.
17+
18+
public func binarySearch<T: Comparable>(_ a: [T], key: T, range: Range<Int>) -> Int? {
19+
if range.lowerBound >= range.upperBound {
20+
return nil
21+
} else {
22+
let midIndex = range.lowerBound + (range.upperBound - range.lowerBound) / 2
23+
if a[midIndex] > key {
24+
return binarySearch(a, key: key, range: range.lowerBound ..< midIndex)
25+
} else if a[midIndex] < key {
26+
return binarySearch(a, key: key, range: midIndex + 1 ..< range.upperBound)
27+
} else {
28+
return midIndex
29+
}
30+
}
31+
}
32+
33+
/**
34+
The iterative version of binary search.
35+
36+
Notice how similar these functions are. The difference is that this one
37+
uses a while loop, while the other calls itself recursively.
38+
**/
39+
40+
public func binarySearch<T: Comparable>(_ a: [T], key: T) -> Int? {
41+
var lowerBound = 0
42+
var upperBound = a.count
43+
while lowerBound < upperBound {
44+
let midIndex = lowerBound + (upperBound - lowerBound) / 2
45+
if a[midIndex] == key {
46+
return midIndex
47+
} else if a[midIndex] < key {
48+
lowerBound = midIndex + 1
49+
} else {
50+
upperBound = midIndex
51+
}
52+
}
53+
return nil
54+
}

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ Language| Java | Python | Rust | C | C++ | JavaScript | Go | C# | Ruby | Swift
1010
A*Search | | :+1: | | | :+1: | | | |
1111
BellmanFord | :+1: | | | | :+1: | | | |
1212
BestFirstSearch | :+1: | | | | | | | | :+1: |
13-
BinarySearch | :+1: | :+1: | | :+1: | :+1: | :+1: | :+1: | | :+1: |
13+
BinarySearch | :+1: | :+1: | | :+1: | :+1: | :+1: | :+1: | | :+1: | :+1:
1414
Bitap Algorithm | | :+1: | | | :+1: | | | |
1515
BreadthFirstSearch | :+1: | :+1: | | :+1: | | | | |
1616
Borwein's Algorithm | :+1: | | | | :+1: | | | | ||

0 commit comments

Comments
 (0)