Skip to content

Instantly share code, notes, and snippets.

@amanmeghrajani
Created August 30, 2018 00:25
Show Gist options
  • Save amanmeghrajani/0ee0de8f4925a9ae46a6cf7fea82d5a0 to your computer and use it in GitHub Desktop.
Save amanmeghrajani/0ee0de8f4925a9ae46a6cf7fea82d5a0 to your computer and use it in GitHub Desktop.
// takes O(log(n) base 2 + 1) iterations where 2 ^ n is the closest to array.count
// example 10 is closest to 2^3 which will take 3 + 1 iterations to find an element in the worst case scenario
func iterativeBinarySearch (_ array: [Int],_ key: Int) -> Int? {
var low = 0;
var high = array.count - 1
var mid : Int;
// var iterations = 0;
while low <= high {
mid = (high - low) / 2 + low // high - low, gives you diff. /2 gives you mid. + low gives you exact index
// iterations += 1;
if(key == array[mid]) {
// print(iterations)
return mid
} else if (key < array[mid]) {
high = mid - 1
} else {
low = mid + 1
}
}
return -1
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment