I have an array of sorted integers, and I'd like to get the two consecutive indices of elements that bound a particular value I pass in. To illustrate, because it's hard to describe in words, let's say I have an array (regular zero-indexed):
1 3 4 5 7 9
I want to get the two indices that bound, say, the value 6. In this case, the array has values 5 and 7 in consecutive positions, which bound the value I'm looking for (5 <= 6 <= 7), and so I'd return the index of 5 and the index of 7 (3 and 4, respectively).
I have this currently implemented in a very brute-force fashion, involving a lot of sorts and searches in the array. In addition, I feel like I'm missing a lot of corner cases (especially with values that are larger/smaller than the largest/smallest value in the array).
Is there an elegant way of doing this? What corner cases should I look out for, and how can I deal with and or check for them? Thanks!