diff --git a/Binary Search/BinarySearch.swift b/Binary Search/BinarySearch.swift index d6623e355..b67000fe9 100644 --- a/Binary Search/BinarySearch.swift +++ b/Binary Search/BinarySearch.swift @@ -14,17 +14,17 @@ import Foundation // The recursive version of binary search. public func binarySearch(_ a: [T], key: T, range: Range) -> Int? { - if range.lowerBound >= range.upperBound { + guard range.lowerBound < range.upperBound else { return nil + } + + let midIndex = range.lowerBound + (range.upperBound - range.lowerBound) / 2 + if a[midIndex] > key { + return binarySearch(a, key: key, range: range.lowerBound ..< midIndex) + } else if a[midIndex] < key { + return binarySearch(a, key: key, range: midIndex + 1 ..< range.upperBound) } else { - let midIndex = range.lowerBound + (range.upperBound - range.lowerBound) / 2 - if a[midIndex] > key { - return binarySearch(a, key: key, range: range.lowerBound ..< midIndex) - } else if a[midIndex] < key { - return binarySearch(a, key: key, range: midIndex + 1 ..< range.upperBound) - } else { - return midIndex - } + return midIndex } } diff --git a/Binary Search/README.markdown b/Binary Search/README.markdown index 0cecce6cf..eb37ea000 100644 --- a/Binary Search/README.markdown +++ b/Binary Search/README.markdown @@ -58,26 +58,17 @@ Here is a recursive implementation of binary search in Swift: ```swift func binarySearch(_ a: [T], key: T, range: Range) -> Int? { - if range.lowerBound >= range.upperBound { - // If we get here, then the search key is not present in the array. + guard range.lowerBound < range.upperBound else { return nil - + } + + let midIndex = range.lowerBound + (range.upperBound - range.lowerBound) / 2 + if a[midIndex] > key { + return binarySearch(a, key: key, range: range.lowerBound ..< midIndex) + } else if a[midIndex] < key { + return binarySearch(a, key: key, range: midIndex + 1 ..< range.upperBound) } else { - // Calculate where to split the array. - let midIndex = range.lowerBound + (range.upperBound - range.lowerBound) / 2 - - // Is the search key in the left half? - if a[midIndex] > key { - return binarySearch(a, key: key, range: range.lowerBound ..< midIndex) - - // Is the search key in the right half? - } else if a[midIndex] < key { - return binarySearch(a, key: key, range: midIndex + 1 ..< range.upperBound) - - // If we get here, then we've found the search key! - } else { - return midIndex - } + return midIndex } } ```