Last active
April 26, 2017 05:35
-
-
Save jamesrochabrun/8cd9a0b5bd1447949fa78ad739f452bf to your computer and use it in GitHub Desktop.
binary search in array of strings sorted alphabetically
This file contains hidden or 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
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