Created
August 22, 2018 06:00
-
-
Save aniltv06/9866734694382d7a2df2f4bed5ce91ea to your computer and use it in GitHub Desktop.
Binary search written in swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func binarySearch<T: Comparable>(_ a: [T], key: T, range: Range<Int>) -> Int? { | |
if range.lowerBound >= range.upperBound { | |
// If we get here, then the search key is not present in the array. | |
return nil | |
} 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 | |
} | |
} | |
} | |
let numbers = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67] | |
binarySearch(numbers, key: 43, range: 0 ..< numbers.count) // gives 13 | |
func linearSearch<T: Equatable>(_ a: [T], _ key: T) -> Int? { | |
for i in 0 ..< a.count { | |
if a[i] == key { | |
return i | |
} | |
} | |
return nil | |
} | |
linearSearch(numbers, 43) // returns 13 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment