Showing posts with label linear. Show all posts
Showing posts with label linear. Show all posts

Sunday, April 6, 2014

Java code to search an element using Linear Search or Binary Search

/*
Program to search for a number in an array entered by the user using
either Linear Search or Binary Search.
*/
import java.io.*;
class searchArray
{
int a[];
int n;
static BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
public searchArray(int nn) // Constructor
{
a = new int[nn];
n = nn;
}
public static void main(String args[]) throws IOException
{
System.out.print("
Enter the size of the array : ");
int nn = Integer.parseInt(br.readLine());
searchArray call = new searchArray(nn);
System.out.println("
Enter " +nn +" elements :");
call.readArray();
// Ask for the search technique
System.out.println("Choose Search Technique :
");
System.out.println("1 : Linear Search");
System.out.println("2 : Binary Search (the array should be
sorted in ascending order)");
System.out.print("
Your Choice : ");
int choice = Integer.parseInt(br.readLine());
int v;
switch(choice)
{
case 1:
System.out.print("
Enter the number to be searched : ");
v = Integer.parseInt(br.readLine());
call.linearSearch(v);
break;
case 2:
System.out.print("
Enter the number to be searched : ");
v = Integer.parseInt(br.readLine());
call.binarySearch(v);
break;
default :
System.out.println("
Invalid Choice !");
break;
}
}
public void readArray() throws IOException
{
for(int i=0;i<n;i++)
a[i] = Integer.parseInt(br.readLine());
}
public void linearSearch(int v)
{
int f=-1;
for(int i=0;i<n;i++)
{
if(a[i]==v)
{
f=i;
break;
}
}
if(f==-1)
System.out.println("
" +v +" NOT found !");
else
System.out.println("
" +v +" is in location " +f);
}
public void binarySearch(int v)
{
int f=-1;
int l=0,m=0,u=n-1;
while(l<=u && f==-1)
{
m = (l+u)/2;
if(a[m]==v)
f = m;
else
if(a[m]>v)
u = m-1;
else
l = m+1;
}
if(f==-1)
7System.out.println("
" +v +" NOT found !");
else
System.out.println("
" +v +" is in location " +m);
}
}
/**
* Algorithm for Linear Search :
* ---------------------------
* 1. Start
* 2. Construct a single-dimensional array of appropriate size.
* 3. Fill the array with data entries.
* 4. Ask the user for the number to be searched
* 5. Use linear search technique.
* 6. Print a message whether the number is present in the array or
not.
* 7. End
*
* Algorithm for Binary Search :
* ---------------------------
* 1. Start
* 2. Construct a single-dimensional array of appropriate size.
* 3. Fill the array with data entries in ascending order.
* 4. Ask the user for the number to be searched.
* 5. Use binary search technique.
* 6. Print a message whether the number is present in the array or
not.
* 7. End
*/
/*
Enter the size of the array : 5
Enter 5 elements :
46
324
846
54
541
Choose Search Technique :
1 : Linear Search
2 : Binary Search (the array should be sorted in ascending order)
Your Choice : 1
Enter the number to be searched : 54
54 is in location 3
*/


Read More..