D
D
Dmitry Mitin2018-04-24 11:56:21
recursion
Dmitry Mitin, 2018-04-24 11:56:21

How to do a recursive binary search?

Good afternoon.
I'm sitting for the second day and I can't figure out how to write a recursive binary search.
The task is as follows, find the index of the left border
5adef035ec2ca831369234.png
, and if the required element is not in the table, return -1;
The code must be exactly recursive.

private static int FindLeftBorder(long[] arr, long value)
{
  return BinSearchLeftBorder(arr, value, -1, arr.Length);
}

I wrote the code, but I can't figure out how to return -1?
public static int BinSearchLeftBorder(long[] array, long value, int left, int right)
    {
      if (left == right) return left;
      var m = (left + right) / 2;
      if (array[m] < value)
        return BinSearchLeftBorder(array, value, m, right-1 );
      return BinSearchLeftBorder(array, value, left, m);
    }

I'm still a very beginner amateur, so I apologize right away for the stupidity of this question.
Thanks in advance everyone for your reply!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
AlexHell, 2018-05-03
@AlexHell

the meaning of binary search is a gradual shift of boundaries, i.e. [0, 10] the interval for array turns into [0, 5] then into [2, 5] then into [4,5] then the element [4] is checked
for accuracy , but what comes to mind is
public static int BinSearchLeftBorder(long[] array, long value, int left, int right)
{
if (left == right)
{
if (array[left] == ​​value) return left;
return -1;
}
var m = (left + right) / 2;
if (array[m] < value)
return BinSearchLeftBorder(array, value, m, right-1 );
return BinSearchLeftBorder(array, value, left, m);
}
although at the expense of the condition "index of the left border", in my opinion, my option, and any common one does not guarantee exactly the left occurrence, the index will be selected as it hits, maybe on the middle 2 of 3 twos, so it is also possible to rotate the additional search bin to the left, or somehow build an algorithm
for your example with 2 right in the middle, the normal bin-search will end immediately at the 1st step and find the value == 2 in the index [4].

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question