From 95b9d3df6ebdab191d0f559d5eaf411748e89afb Mon Sep 17 00:00:00 2001 From: Marwan Alani Date: Thu, 11 Oct 2018 23:49:48 -0400 Subject: [PATCH] [Improvement] Added example for Binary Search in `Swift` --- .../search-algorithms/binary-search/index.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/client/src/pages/guide/english/algorithms/search-algorithms/binary-search/index.md b/client/src/pages/guide/english/algorithms/search-algorithms/binary-search/index.md index af453e2222..b3c5e5da37 100644 --- a/client/src/pages/guide/english/algorithms/search-algorithms/binary-search/index.md +++ b/client/src/pages/guide/english/algorithms/search-algorithms/binary-search/index.md @@ -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 * [Binary search (YouTube video)](https://youtu.be/P3YID7liBug) * [Binary Search - CS50](https://www.youtube.com/watch?v=5xlIPT1FRcA)