Monday, 27 October 2014

binary search algorithm in java

Structure of the Problem Requirements 

In this Program we will learn how to implement binary search algorithm in Java. Binary search or half-interval search algorithm is used to find the position of the specific elements in a given data structure.Binary search follow divide and conquer strategy. In this problem we asked user to input the array size and after creating array again asked user to enter a value to search in array. Here is the source code of this problem which help you in better understanding.
                                

                                 SOURCE CODE




import java.io.*;
class Operate
{
int ret=-1;
int bsearch(int a[],int first,int last,int key)
{
int mid;
mid=(first+last)/2;
if(first<=last)
{
if(a[mid]==key)
ret=mid;
else if(a[mid]>key)
bsearch(a,first,mid-1,key);
else
bsearch(a,mid+1,last,key);
}

return ret;
}
}
public class Binary
{
public static void main(String args[]) throws IOException
{
Operate op=new Operate();
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
int n,i,k,key;
int a[]=new int[50];
System.out.println("\n Enter n value:");
n=Integer.parseInt(br.readLine());
System.out.println(" \n Enter elements  into array:");

for(i=0;i<n;i++)
a[i]=Integer.parseInt(br.readLine());

System.out.println(" \n Enter key to search:");

key=Integer.parseInt(br.readLine());

k=op.bsearch(a,0,n-1,key);
if(k!=-1)
System.out.println("\nThe element "+key+" present at "+k);
else
System.out.println("\nElement not found in the array");
}
}


                     OUTPUT OF THE PROGRAM
Binary search in Java
Binary search in Java




Share it Please
asad

About Author!

Asad Niazi is Software Engineer , Programmer, Web Developers and a young mentor of Tech Solutions Desk and Blogging Solutions . Asad Love to writes about Technology, Programming, Blogging and make money online.

0 comments:

Post a Comment