Skip to content

Instantly share code, notes, and snippets.

@jamesrochabrun
Last active April 26, 2017 05:35
Show Gist options
  • Save jamesrochabrun/8cd9a0b5bd1447949fa78ad739f452bf to your computer and use it in GitHub Desktop.
Save jamesrochabrun/8cd9a0b5bd1447949fa78ad739f452bf to your computer and use it in GitHub Desktop.
binary search in array of strings sorted alphabetically
var arr = ["a", "abc", "aabc", "aabbc", "aaabbbcc", "bacc", "bbcc", "bbbccc", "cb", "cbb", "cbbc", "d" , "defff", "deffz"]
func binarySearch(_ array: [String], value: String) -> String {
var firstIndex = 0
var lastIndex = array.count - 1
var wordToFind = "Not founded"
var count = 0
while firstIndex <= lastIndex {
count += 1
let middleIndex = (firstIndex + lastIndex) / 2
let middleValue = array[middleIndex]
if middleValue == value {
wordToFind = middleValue
return wordToFind
}
if value.localizedCompare(middleValue) == ComparisonResult.orderedDescending {
firstIndex = middleIndex + 1
}
if value.localizedCompare(middleValue) == ComparisonResult.orderedAscending {
print(middleValue)
lastIndex = middleIndex - 1
}
}
return wordToFind
}
//print d
print(binarySearch(arr, value: "d"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment