pls someone send the code for binary search
Answers
JAVA CODE :
import java.util.*;
class binary_search
{
public static void main(String args[ ])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number of elements in the array");
int n=sc.nextInt();
int a[]=new int[n];
System.out.println("Enter the array elements");
for(int i=0;i<n;i++)
{
a[i]=sc.nextInt();
}
System.out.println("Enter the element that needs to be searched");
int ele=sc.nextInt();
int f=0;
int l=n-1;
int mid=(f+l)/2;
while(f<=l)
{
if(a[mid]==ele)
{
System.out.println("Search successful");
System.out.println("Present at="+(mid+1));
break;
}
else if(ele>a[mid])
{
f=mid+1;
}
else if(ele<a[mid])
{
l=mid-1;
}
mid=(f+l)/2;
}
if(f>l)
{
System.out.println("Search unsuccessful");
}
}
}
-------------------------------------------------------------------
OUTPUT :
Enter the number of elements in the array
4
Enter the elements
1
2
3
4
Enter the element to be searched
3
Search successful
Present at 3
Hope it helps : )
_____________________________________________________________