1)write java programs that use recursive function for implementing Linear Search method?
import java.util.*;
class RecursiveLinearSearchDemo
{
static int[] a;
static int key;
public static void main(String args[])
{
int i,num;
Scanner input=new Scanner(System.in);
System.out.println("enter no of items");
num=input.nextInt();
a=new int[num];
System.out.println("enter " + num + "items");
for(i=0;i<num;i++)
a[i]=input.nextInt();
System.out.println("enter element u want to search");
key=input.nextInt();
if( linearSearch(a.length-1) )
System.out.println(key + " found in the list" );
else
System.out.println(key + " not found in the list");
}
static boolean linearSearch(int n)
{
if( n < 0 ){
return false;
}
if(key == a[n]){
return true;
}
else{
return linearSearch(n-1);
}
}
}
No comments:
Post a Comment