From 2af136beea57cc0da9c5d580483ed7bf9a25b88d Mon Sep 17 00:00:00 2001 From: a7madyg Date: Sat, 31 Oct 2020 10:49:32 +0300 Subject: [PATCH] Added binary search in swift --- Swift/Algorithms/binary_search.swift | 30 ++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 Swift/Algorithms/binary_search.swift diff --git a/Swift/Algorithms/binary_search.swift b/Swift/Algorithms/binary_search.swift new file mode 100644 index 00000000..9e38cf67 --- /dev/null +++ b/Swift/Algorithms/binary_search.swift @@ -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)") +} \ No newline at end of file