Monday 2 February 2015

RecursiveLinearSearchDemo


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);
}

}
}

LINEAR SEARCH


1) write java programs that use non-recursive function for implementing Linear Search  method?

import java.util.Scanner;
class Linear
{
public static void main(String ar[])
{
int i,n,item,a[];
Scanner sc=new Scanner(System.in);
System.out.println("enter the size of the array");
n=sc.nextInt();
a=new int[n];
System.out.println("enter " + n + "  values");
for(i=0;i<n;i++)
a[i]=sc.nextInt();
System.out.println("enter element u want to search");
item=sc.nextInt();
for(i=0;i<n;i++)
{
if(a[i]==item)
{
System.out.println(item + "   found at index    " + i);
break;
}
}
if(i==n)
{
System.out.println("element not found");
}
}
}