- #1
anyonebutangel
- 40
- 5
Summary:: I have to solve this problem stirctly according to the question that follows:
Mentor note: I edited the original code to add indentation and a few blank lines to make the code more readable, so line 43 is no longer the line in question.
so this is the question i tried but it gives error in line 43 of my program it is only when the element to be searched is not present int the array while it must print "ELEMENT NOT FOUND "message if the element is absent .
foollowing is my program and output.
and the output
[/code]
Mentor note: I edited the original code to add indentation and a few blank lines to make the code more readable, so line 43 is no longer the line in question.
so this is the question i tried but it gives error in line 43 of my program it is only when the element to be searched is not present int the array while it must print "ELEMENT NOT FOUND "message if the element is absent .
foollowing is my program and output.
Java:
import java.io.*;
class Binsearch
{
int arr[];
int n;
static BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
Binsearch(int nn)
{
n=nn;
arr=new int[nn];
}
void fillarray()throws IOException
{
System.out.println("ENTER THE ELEMENTS OF ARRAY");
for(int i=0;i<n;i++)
{
arr[i]=Integer.parseInt(br.readLine());
}
} //end of method
void sort()
{
int temp=0;
for(int i=0;i<n;i++)
{
for(int j=0;j<n-1;j++)
{
if(arr[j]>arr[j+1])
{
temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
}
int bin_search(int l,int u,int v)
{
int m=(l+u)/2;
System.out.println("m="+m+"l="+l+"u="+u+"v="+v);
if(arr[m]==v)
return(m);
else if(arr[m]>v)
return(bin_search(0,m,v));
else if(arr[m]<v)
return(bin_search(u,m,v));
else
return(-1);
}
public static void main(String args[])throws IOException
{
System.out.println("ENTER THE NUMBER OF ELEMENTS");
Binsearch ob=new Binsearch(Integer.parseInt(br.readLine()));
ob.fillarray();
ob.sort();
System.out.println("ENTER THE NUMBER TO BE SEARCHED");
int r=0;
r=ob.bin_search(0,ob.n,Integer.parseInt(br.readLine()));
System.out.println("THE SORTED ARRAY IS:");
for(int i=0;i<ob.n;i++)
System.out.print(ob.arr[i]+"\t");
System.out.println();
System.out.println("THE VALUE OF R IS:"+r);
if(r==-1)
{
System.out.println("ELEMENT NOT FOUND");
}
else
{
System.out.println("ELEMENT FOUND AT "+r);
}
} //end of main
}
Attachments
Last edited by a moderator: