Last active
September 25, 2017 03:04
-
-
Save wadejensen/67a9e469685145139d16eee349f33381 to your computer and use it in GitHub Desktop.
Scala binary search for exact match or neighbour on floating point numbers
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
/** | |
* A functional binary tree search for floating point numbers which finds | |
* a neighbour to the search target in the given list. | |
* Returns upper or lower index if target is outside min and max of list. | |
* @param start Lower index of the array to search | |
* @param end Upper index of the array to search | |
* @param target Value being searched for in list | |
* @param list Sorted list of values to search | |
* @return Index of a neighbour to the target within list | |
* (not guaranteed to be nearest neighbour) | |
*/ | |
def binarySearch(start: Int = 0, | |
end: Int, | |
target:Double, | |
list: Array[Double]): Int = { | |
// midpoint with overflow protection | |
val mid = start + (end-start+1)/2 | |
// if mid is the same as start or finish then we have found a neighbour | |
if ( mid == start || mid == end) mid | |
else if ( target > list(mid) ) binarySearch(mid, end, target, list) | |
else if ( target < list(mid) ) binarySearch(start, mid, target, list) | |
else if ( target == list(mid) ) mid | |
else -1 // Your list has NaNs in it and you have bigger problems | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment