Write a Java program to search an element using binary search using array.
Write a Java program to search an element using binary search using array.
Program:
import java.util.*;
public class Binary_Search
{
public static void main(String args[])
{
int n, i, search, first, last, middle;
int a[] = new int[50];
Scanner sc= new Scanner(System.in);
System.out.println("Enter the Number of Elements u want: ");
n = sc.nextInt();
System.out.println("Note : please,Enter elements of an array either asending or desending order.");
System.out.println("Enter " +n+ " Elements :");
for(i=0; i<n; i++)
{
a[i] = sc.nextInt();
}
System.out.println("Enter a key value to Search:");
search = sc.nextInt();
//Binary search
first = 0;
last = n-1;
middle = (first+last)/2;
while(first <= last)
{
if(a[middle] < search)
{
first = middle+1;
}
else if(a[middle] == search)
{
System.out.println(search+ " Found at Location " +(middle+1));
break;
}
else
{
last = middle - 1;
}
middle = (first+last)/2;
}
if(first > last)
{
System.out.println("Not Found..!! " +search+ " is not Present in the List.");
}
}
}
Output :
Enter the Number of Elements u want:
6
Note : please,Enter elements of an array either asending or desending order
Enter 6 Elements :
1
2
3
5
10
15
Enter a key value to Search:
5
5 Found at Location 4
Or
Enter the Number of Elements u want:
5
Note : please,Enter elements of an array either asending or desending order
Enter 5 Elements :
1
2
3
5
15
Enter a key value to Search:
7
Not Found..!! 7 is not Present in the List.
Comments
Post a Comment