Pageviews

Saturday 24 August 2013

Binary search program in Java

by Unknown  |  in Source Codes at  Saturday, August 24, 2013

Binary search:It is the advanced and efficient searching technique as compared to Linear search.In this technique the elements are entered in sorted form.It does not compare each and every element,it firstly calculates the mid of the list and if the element is less than mid then it refines searches only to the left of the mid,if the element is greater than the mid then the search is done only from the elements present at the right of the mid.

Java program code :

import java.util.Scanner;
class binary
{
public static void main(String args[])
{
int i,mid=0;
Scanner k=new Scanner(System.in);
System.out.println("Enter number of elements you want to insert");
int n=k.nextInt();
int first=0,last=n-1;
mid=last-first/2;
int []ar=new int[n];
System.out.println("Enter elements of the list in sorted form");
for(i=0;i<ar.length;i++)
{
ar[i]=k.nextInt();
}
System.out.println("Enter element you want to search");
int item=k.nextInt();
int flag=0;
for(i=0;i<n;i++)
{
if(ar[i]==item)
{
flag=1;
break;
}
if(ar[i]<item)
{
last=mid+1;
}
else
{
first=mid-1;
}
}
if(flag==1) 
{System.out.println("Item found at " + i + " location");   } 
else
{
System.out.println("Item not found");}
}

}

Output of the program:

Binary search

Advantages of Binary search:


  • It is fast,time saving and efficient searching technique.











0 comments:

Proudly Powered by Blogger.