Non-Recursive:
import
java.util.Scanner;
public
class LinearSearch {
public static void main(String[] ar) {
int len, s, a[], x;
Scanner input = new Scanner(System.in);
System.out.print(" \n Enter the
length of array : ");
x = input.nextInt();
a = new int[x];
System.out.println(" \n Enter
Elements : ");
for(int i=0; i<x; i++)
a[i] = input.nextInt();
System.out.print(" \n Enter the
item to be search : ");
s = input.nextInt();
for(int i=0; i<x; i++) {
if(s == a[i]) {
System.out.println(" \n
Item " + s +" found at position : " + (i+1));
return;
}
}
System.out.println(" \n Item
" + s + " not found. \n");
} //End of main()
} //End of
LinearSearch class
Output:
Recursive:
import
java.util.Scanner;
public
class LinearSearchRec {
public static int a[], size;
private LinearSearchRec(int len) {
size = len;
a = new int[size];
}
private int search(int[] a, int index , int
key) {
if(size == index)
return 0;
if(a[index] == key)
return ++index;
return search(a, ++index, key);
}
private void input() {
Scanner input = new
Scanner(System.in);
System.out.println("\n Enter
elements : ");
for(int i=0; i<size; i++)
a[i] = input.nextInt();
}
public static void main(String[] ar) {
Scanner input = new
Scanner(System.in);
System.out.print(" \n Enter
length : ");
int x = input.nextInt();
LinearSearchRec linearSearchRec = new
LinearSearchRec(x);
linearSearchRec.input();
System.out.print(" Enter search
element : ");
int search = input.nextInt();
int temp = linearSearchRec.search(a ,
0, search);
if(temp == 0)
System.out.println ("\n Item
" + search + " not found.");
else
System.out.println("\n Item
" + search + " found at position " + temp);
} //End of main()
} //End of
LinearSearchRec class
Output:


No comments:
Post a Comment