Thursday, September 24, 2015

Program to find a numbuer using Binary Search.

import java.io.*;
class BinarySearch
{
public static void main(String args[])
{
int item,n,first,last,i,mid;
int a[] = new int[15];
DataInputStream r = new DataInputStream(System.in);
try
{
System.out.println("Enter the size of list:");
n = Integer.parseInt(r.readLine());
first=0;
last=n-1;
System.out.println("Enter the numbers in the sorted form:");
for(i=0;i<n;i++)
{
a[i] = Integer.parseInt(r.readLine());
}
mid=(first+last)/2;
System.out.println("Enter the search value:");
item = Integer.parseInt(r.readLine());
while(first<=last)
{
if(item == a[mid])
{
System.out.println("Number is at Location "+(mid));
break;
}
else if(item>=a[mid])
{
first=mid+1;
}
else
{
last=last-1;

}
mid=(first+last)/2;
}
if(first>last)
{
System.out.println("Number is not found");
}
else
{
System.out.println("Number found successfully");
}
}
catch(Exception e)
{
System.out.println("error is occur at"+e);
}
}
}

Output:


No comments:

Post a Comment