Answer the question
In order to leave comments, you need to log in
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
, 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);
}
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);
}
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question