Skip to content

Commit

Permalink
Added binary search in swift
Browse files Browse the repository at this point in the history
  • Loading branch information
Faaatman committed Oct 31, 2020
1 parent b2b14e0 commit 2af136b
Showing 1 changed file with 30 additions and 0 deletions.
30 changes: 30 additions & 0 deletions Swift/Algorithms/binary_search.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
// Binary search | Swift
func binarySearch(in numbers: [Int], for value: Int) -> Int?
{
var left = 0
var right = numbers.count - 1

while left <= right {

let middle = Int(floor(Double(left + right) / 2.0))

if numbers[middle] < value {
left = middle + 1
} else if numbers[middle] > value {
right = middle - 1
} else {
return middle
}
}

return nil
}
// Driver code
let numbers = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
let value = 17

if let index = binarySearch(in: numbers, for: value) {
print("Found \(value) at index \(index)")
} else {
print("Did not find \(value)")
}

0 comments on commit 2af136b

Please sign in to comment.