Find an element in the list using a binary search algorithm.
So I thought perhaps it returns the list item, kind of like find() vs index(). But nope, binaryFind() returns an Int same as binarySearch().
They both do similar things and I'm not sure why I would use binaryFind() over binarySearch().
brianMon 8 Feb 2016
So I thought perhaps it returns the list item, kind of like find() vs index(). But nope, binaryFind() returns an Int same as binarySearch().
Actually your first thought is correct. binarySearch is used when the values themselves are the key - you are passing one of the values in the list to lookup its index. The list is ordered by the values themselves.
Where as binaryFind is just like find except it uses a binary search based on the fact that you have the values sorted by some "other" key value
So for practical purposes binarySearch works just like index except is a binary search versus a linear search (instances are key). And binaryFind works just like find excepts is a binary search versus linear (func determines key). In retrospect it might have been nice to keep naming consistent, but not sure I would make a breaking change for that
SlimerDudeWed 10 Feb 2016
Cool, thanks for the explanation. The bit that made the difference clear was:
binarySearch(): the list is ordered by the values themselves
binaryFind(): the values sorted by some "other" key value
SlimerDude Sun 7 Feb 2016
An easy one this!
Just to say I find the docs for List.binaryFind() a tad confusing, especially when compared to List.binarySearch().
The
binaryFind()
docs start off by saying:So I thought perhaps it returns the list item, kind of like
find()
vsindex()
. But nope,binaryFind()
returns anInt
same asbinarySearch()
.They both do similar things and I'm not sure why I would use
binaryFind()
overbinarySearch()
.brian Mon 8 Feb 2016
Actually your first thought is correct. binarySearch is used when the values themselves are the key - you are passing one of the values in the list to lookup its index. The list is ordered by the values themselves.
Where as binaryFind is just like find except it uses a binary search based on the fact that you have the values sorted by some "other" key value
So for practical purposes binarySearch works just like index except is a binary search versus a linear search (instances are key). And binaryFind works just like find excepts is a binary search versus linear (func determines key). In retrospect it might have been nice to keep naming consistent, but not sure I would make a breaking change for that
SlimerDude Wed 10 Feb 2016
Cool, thanks for the explanation. The bit that made the difference clear was: