Apply Binary search and search for element 18.
11, 12, 13, 14, 15, 16, 17, 18, 19.
Answers
Answered by
0
Answer:
Program:-
import java.util.*;
public class Main
{
public static void main(String args[])
{
Scanner in=new Scanner(System.in);
int a[]={11,12,13,14,15,16,17,18,19};
int lb=0,ub=8,p=0,ns,f=0;
System.out.println("Enter the number to be searched");
ns=in.nextInt();
while(lb<=ub)
{
p=(lb+ub)/2;
if(a[p]<ns)
lb=p+1;
if(a[p]>ns)
ub=p-1;
if(a[p]==ns)
{
f=1;
break;
}
}
if(f==1)
System.out.println("Search successful the number "+ns+" is present");
else
System.out.println("Search unsuccessful the number "+ns+" is not present");
}
}
Note:-
- Binary Search is comparatively faster than Linear search.
- Only disadvantage of Binary Search is that it only works for sorted arrays.
Attachments:
Similar questions
Science,
21 days ago
Physics,
1 month ago
English,
9 months ago
Math,
9 months ago
Computer Science,
9 months ago