I’m using Tcl. I have a sorted list of real numbers. Given the number n I need to find an index of the list element which is:
- either less of equal to
n; - or greater than
n.
Is there any standard way to do this? lsearch expects exact match and can’t be used.
With Tcl 8.6 (still in beta) lsearch will do what your asking, the
-sortedand new-bisectoptions allow the following:For Tcl versions prior to 8.6 your going to have to roll your own code, given that the list is sorted it should be fairly straightforward to write a binary search with the properties that you require, Rosetta code here contains a description of a pure binary search and also a Tcl implemention. You should be able to use this as your starting point.
Here is a very quick version I created, it returns the index of either the value you search for or the value greater than it. The exception to watch for is the end of the list, searching for a value beyond the largest element returns the largest element. It’s only had minimal testing so if you do use it do some additional tests! I also don’t stop if the search finds the value, if this is likely to happen often you may want to optimize for this.