import java.io.*;
class Binary {
int i=0, j=0, n=0, t=0, I=0, u=0, x=0, mid=0;
int a[] = new int[100];
DataInputStream s = new DataInputStream(System.in);
void getData(){
System.out.println("Enter the Number of elements");
try{
n = Integer.parseInt(s.readLine());
System.out.println("Enter the Elements");
for(i=0 ; i<n; i++){
a[i] = Integer.parseInt(s.readLine());
}
}catch(Exception e){System.out.println("the Exception Araise ="+e);}
}
void arrange(){
for(i=1 ; i<n; i++){
for(j=1;j<n;j++){
if(a[i]>a[j]){
t = a[i];
a[i] = a[j];
a[j] = t;
}
}
}
}
void search(){
I = 1;
u = n;
System.out.println("Enter the Elements to be searched");
try{
x = Integer.parseInt(s.readLine());
}catch(Exception e){System.out.println("Exception araise ="+e);}
while(I<u){
mid = (i+u) / 2;
if(a[mid] == x){
System.out.println("The Element is found on "+mid+" Location");
System.exit(1);
}
else if(x > a[mid]){
I = mid + 1;
}
else {u = mid-1;}
}
System.out.println("Element is not Found");
}
}
public class BinarySearch{
public static void main(String args[])throws IOException{
Binary a = new Binary();
a.getData();
a.arrange();
a.search();
}
}
No comments:
Post a Comment