In: Computer Science
Write a pseudocode or java code implementation for
linear search that searches elements based on a key value from an
array of undetermined length
JAVA
import java.util.*;
// for using Scanner
class
class LinearSearch
{
public static void main(String args[])
{
Scanner obj = new
Scanner(System.in);
// making Scanner class
object
System.out.print("How many elements
do you want to enter : ");
// asking for input size
int size =
obj.nextInt();
// taking input of size
System.out.println("\nEnter the
elements of the array : ");
// asking for entering array
elements
ArrayList
for(int i=0;i
int x =
obj.nextInt();
// taking input of array elements
arr.add(x);
// adding input to dynamic array
}
System.out.println("\nEnter the key
value to search in the array : ");
// Enter key value to search in the array
int key =
obj.nextInt(); //
taking input of key to be searched
int found=0;
// for
status of key found or not
int index=0;
// storing
index of key to be found
for(int
i=0;i
if(arr.get(i)==key)
// if key found in the array
{
found=1;
// status of found = 1
index = i;
// storing index of key in
the array
break;
}
}
if(found==1)
// if key found in the
array
System.out.println("Key found at index "+index);
else
// if key not found in the array
System.out.println("Key not found in the array");
}
}
Output :