Skip to content

Instantly share code, notes, and snippets.

@Daemon-Devarshi
Last active July 26, 2017 06:16
Show Gist options
  • Save Daemon-Devarshi/81b55b9487819510a846787dd62361de to your computer and use it in GitHub Desktop.
Save Daemon-Devarshi/81b55b9487819510a846787dd62361de to your computer and use it in GitHub Desktop.
Binary Search using Recurssion
/// Performs binary search using Recursion
func binarySearch<T:Comparable>(on array: [T], for targetValue: T, from minIndex: Int, to maxIndex: Int) -> Int? {
// assigning to var so that values can be updated
var min = minIndex
var max = maxIndex
// Obtaining the pivot element
let guessIndex = Int((max + min) / 2)
// Value comparisons
if array[guessIndex] == targetValue {
// Value found :) Return the index!
return guessIndex
} else {
// Value not found :( Update min or max index
if targetValue > array[guessIndex] {
// Value lies in upper half, hence update the min
min = guessIndex + 1
} else {
// targetValue < array[guess]
// Value lies in lower half, hence update the max
max = guessIndex - 1
}
if max >= min {
// Complete array still not parsed
return binarySearch(on: array, for: targetValue, from: min, to: max)
} else {
// Complete array parsed, value not found, return -1
return nil
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment