Skip to content

Commit d50d175

Browse files
author
prokhorovxo
authored
Merge pull request #1 from prokhorovxo/prokhorovxo-patch-1
Update BinarySearch.swift
2 parents e592ed6 + b41b80d commit d50d175

File tree

1 file changed

+9
-9
lines changed

1 file changed

+9
-9
lines changed

Binary Search/BinarySearch.swift

+9-9
Original file line numberDiff line numberDiff line change
@@ -14,17 +14,17 @@ import Foundation
1414
// The recursive version of binary search.
1515

1616
public func binarySearch<T: Comparable>(_ a: [T], key: T, range: Range<Int>) -> Int? {
17-
if range.lowerBound >= range.upperBound {
17+
guard range.lowerBound < range.upperBound else {
1818
return nil
19+
}
20+
21+
let midIndex = range.lowerBound + (range.upperBound - range.lowerBound) / 2
22+
if a[midIndex] > key {
23+
return binarySearch(a, key: key, range: range.lowerBound ..< midIndex)
24+
} else if a[midIndex] < key {
25+
return binarySearch(a, key: key, range: midIndex + 1 ..< range.upperBound)
1926
} else {
20-
let midIndex = range.lowerBound + (range.upperBound - range.lowerBound) / 2
21-
if a[midIndex] > key {
22-
return binarySearch(a, key: key, range: range.lowerBound ..< midIndex)
23-
} else if a[midIndex] < key {
24-
return binarySearch(a, key: key, range: midIndex + 1 ..< range.upperBound)
25-
} else {
26-
return midIndex
27-
}
27+
return midIndex
2828
}
2929
}
3030

0 commit comments

Comments
 (0)