Home > Algorithms > Binary Search Implementation with out Recursion

Binary Search Implementation with out 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()
{
printSearchIndex(input);
}

public void printSearchIndex(long [] input)
{
long currElement = 0;
int index = 0;
int startIndex = 0;
int endIndex = input.length;

while(startIndex < endIndex)
{
index = (startIndex + endIndex)/2;
currElement = input[index];

if(currElement > searchElement)
{
endIndex = index - 1;
}else if(currElement < searchElement)
{
startIndex = index + 1;
}else
{
System.out.println("Element found at "+index);
return;
}
}
}

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

}

Advertisements
Categories: Algorithms
%d bloggers like this: