-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinarySearch.swift
More file actions
25 lines (18 loc) · 861 Bytes
/
BinarySearch.swift
File metadata and controls
25 lines (18 loc) · 861 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
extension Array where Element : Comparable, Element : Equatable {
func binarySearch(for element: Element) -> Bool {
// Sort the array and get the middle element
let array = self.sorted()
let mid = array.count / 2
let current = array[mid]
// Check weather the element in the middle is the element we are search for
guard current != element else {
return true
}
// If there are only two elements in the array check if the second element is the element we are searching for
if array.count == 2 { return element == array[1] }
// Create a range for the next array
let range: Range<Int> = (current > element) ? 0 ..< mid : mid ..< array.count
// Recall function with new array
return Array(array[range]).binarySearch(for: element)
}
}