Title: BinarySearch how to find the value in the array between the two neighbors?
Tags: c#;arrays;algorithm;find;binary-search
Question: I have a sorted array double.
The goal is to Find the index in the Array. 
Which contains the value of <= the value of search.

For example the array contains numbers ```{0, 5, 12, 34, 100}``` with index range [0 .. 4].

Search for the value=25. And I want to get the index=2 (range of occurrences of between 12 and 34)

I do not understand how in this case will run a binary search.

```   public class MyComparer : IComparer<double&gt;
    {
        public int Compare(double x, double y)
        {
            //<-------- ???
        }
    }

    public double[] spline_x;

    MyComparer cmpc = new MyComparer();
    int i=Array.BinarySearch(spline_x, x, cmpc);
```


Here is the accepted answer: When binary search does not find item in array, it returns a negative number which is the bitwise complement of the index of the first element that is larger than value. Here is the way you can use it to find range:

```double[] spline_x = { 0D, 5D, 12D, 34D, 100D };
int i = Array.BinarySearch(spline_x, 25);
if (i &gt;= 0)
{
    // your number is in array
}
else
{
    int indexOfNearest = ~i;

    if (indexOfNearest == spline_x.Length)
    {
        // number is greater that last item
    }
    else if (indexOfNearest == 0)
    {
        // number is less than first item
    }
    else
    {
        // number is between (indexOfNearest - 1) and indexOfNearest
    }     
}
```

Comment for this answer: @Mixer keep in mind, that after decrementing *i* you can get `-1` of index of last item of array
Comment for this answer: Thank you.
I'm a bit simplified:

   int i=Array.BinarySearch(spline_x, x);
   if (i= 0)
   {

   }

Here is another answer: Not familiar with C#, but a naive binary search does the trick, finding the last number <= N, which is the boundary you described in question.

```int find_last(int num, const vector<int&gt;&amp;v, size_t begin, size_t end) {
  if (begin &gt;= end) {
    return -1;
  }
  size_t mid = (begin + end) / 2;
  if (v[mid] &gt; num) {
    // [mid, end) is bigger than num, the boundary is in [begin, mid)
    return find_last(num, v, begin, mid);
  }
  // v[mid] is qualified as <= N, search [mid+1, end) for
  // approaching a better boundary if exists.
  size_t index = find_last(num, v, mid+1, end);
  return (index == -1 ? mid : index);
}
```


{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 2, 'CommentCount': 0, 'ContentLicense': 'CC BY-SA 3.0', 'CreationDate': '2013:00:02/18/13', 'FavoriteCount': 3.0, 'PostTypeId': 1, 'Tags': '<c#><arrays><algorithm><find><binary-search>', 'Title': 'BinarySearch how to find the value in the array between the two neighbors?', 'ViewCount': 4391, 'id': 14930881, 'user_AboutMe': None, 'user_AccountId': 2288176.0, 'user_DisplayName': 'Mixer', 'user_Reputation': 1272.0, 'user_Views': 130.0, 'user_id': 2011732.0}}