[Improvement] Added example for Binary Search in Swift
This commit is contained in:
committed by
Kristofer Koishigawa
parent
7cf0899687
commit
95b9d3df6e
@ -286,6 +286,25 @@ int binarySearch(int arr[], int start, int end, int x)
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### Example in Swift
|
||||||
|
```Swift
|
||||||
|
func binarySearch(for number: Int, in numbers: [Int]) -> Int? {
|
||||||
|
var lowerBound = 0
|
||||||
|
var upperBound = numbers.count
|
||||||
|
while lowerBound < upperBound {
|
||||||
|
let index = lowerBound + (upperBound - lowerBound) / 2
|
||||||
|
if numbers[index] == number {
|
||||||
|
return index // we found the given number at this index
|
||||||
|
} else if numbers[index] < number {
|
||||||
|
lowerBound = index + 1
|
||||||
|
} else {
|
||||||
|
upperBound = index
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil // the given number was not found
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
### More Information
|
### More Information
|
||||||
* [Binary search (YouTube video)](https://youtu.be/P3YID7liBug)
|
* [Binary search (YouTube video)](https://youtu.be/P3YID7liBug)
|
||||||
* [Binary Search - CS50](https://www.youtube.com/watch?v=5xlIPT1FRcA)
|
* [Binary Search - CS50](https://www.youtube.com/watch?v=5xlIPT1FRcA)
|
||||||
|
Reference in New Issue
Block a user