Tuesday, March 30, 2010

Binary Search


public class Search
{
/**
The method searches the key in the array passed to it.If the key is
found the position of the key is returned otherwise -1 is returned.
*/
public static int binarySearch(double[] data,double key)
{
int position=-1;
int start=0;
int end=data.length-1;
int middle;
do
{
middle=(start+end)/2;

if(data[middle]==key)
{
//data found
position=middle;
}
else if(data[middle]<key)
{
start=middle+1;
}
else
{
end=middle-1;
}

}
while(start<=end && position==-1);

return position;
}



public static void main(String args[])
{
//calling binarySearch method
//data must be sorted by ascending order for this method to work
double sortedData[]={10,15.5,20,25,25.75,50,77,500,600.99};
double key=50;

int position=Search.binarySearch(sortedData,key);


if(position>=0)
{
System.out.println(key+" is found at position "+position);
}
else
{
System.out.println(key+" is not found in the array");
}

}
}

You can download the code here.

Template by - Abdul Munir | Daya Earth Blogger Template