Write a program for Linear Searching & Binary Searching Array in Java.

Program for linear searching array in core java :

Hello Friends, 

Today I will give you an example for writing a program for  Linear Search array in core java.

Code :

public class linear {
public static void main(String[] args) {
int a[]={1,4,2,6,-4,8,5};
System.out.println(“The element is at location”+Find(a,4));
System.out.println(“The element is at location”+Find(a,-4));
}
public static int Find(int[]a,int key)
{
int i;
for(i=0;i
{
if(a[i]==key)
return i+1;

}
return i-1;
}

}

Output:

The element is at location2
The element is at location5


Write a program for binary searching array in java :

Hello Friends, 

Today I will give you an example for writing a program for Binary Search array in core java.

Code :

public class binary {

public static void main(String[] args) {

int a[]={10,20,30,40,50,60};
int key=40;
Find(a,0,5,key);

}
public static void Find(int[]a,int low,int high,int key)
{
int mid;
if(low>high)
{
System.out.println(“Please Arrange elements in order…!!!”);
return;
}
mid=(low+high)/2;
if(key==a[mid])
System.out.println(“n the element is at the position=”+(mid+1));
else
if(key
Find(a,low,mid-1,key);
else
if(key>a[mid])
Find(a,mid+1,high,key);
}

}

Output :

 the element is at the position=4

Leave a Reply

Your email address will not be published. Required fields are marked *