Home > Algorithms > Implementing Binary Search using Recursion

Implementing Binary Search using Recursion

November 28, 2011


public class BinarySearch
{
private long [] input = {1,2,3,4,5,6,7,8,9,10};
private long searchElement = 10;

public BinarySearch()
{
System.out.println("Element found at index ::"+getSearchIndex(input,0,input.length -1));
}

public long getSearchIndex(long [] input , int beginIndex , int endIndex)
{
int index = (beginIndex + endIndex) / 2;

if(input[index] == searchElement)
{
return index;

}else if(input[index] < searchElement)
{
return getSearchIndex(input,index+1 , endIndex);

}else
{
return getSearchIndex(input,beginIndex ,index - 1);
}
}

public static void main(String[] args)
{
new BinarySearch();
}
}

Advertisements
Categories: Algorithms
%d bloggers like this: