0% completed
Linear Search is one of the simplest searching algorithms. It sequentially checks each element of a list until the desired element is found or the list ends.
Write a Java program to perform a linear search on an array of integers. The program should search for a specific target value and return the index of the target if found. If the target is not present in the array, the program should indicate that the target is not found.
Input:
[4, 2, 7, 1, 3]
7
Output: Target 7 found at index 2.
Justification: The target value 7
is present in the array at index 2
.
Implementing Linear Search involves the following steps:
Initialize Variables:
arr
be the array to search through.target
be the value to search for.foundIndex
be a variable to store the index of the target if found. Initialize it to -1
to indicate that the target hasn't been found yet.Iterate Through the Array:
target
.Check for Target:
target
, assign the current index to foundIndex
and terminate the loop as the target has been found.Result:
foundIndex
is not -1
. If it's not, print the index where the target was found.foundIndex
remains -1
, indicate that the target is not present in the array.Below is the Java code that demonstrates how to perform a linear search on an array of integers.
Initialization:
arr
is initialized with the values {4, 2, 7, 1, 3}
.target
value to search for is set to 7
.Calling the linearSearch
Method:
linearSearch
method is called with arr
and target
as arguments.target
if found; otherwise, it returns -1
.Linear Search Process:
for
loop.arr[i]
, it checks if it equals the target
.i = 2
, arr[2]
is 7
, which matches the target
.2
, indicating that the target is found at index 2
.Result Display:
main
method, the returned index is checked.-1
, it prints that the target 7
is found at index 2
.If Target Not Found:
target
were not present in the array, linearSearch
would return -1
.main
method would then print that the target is not found in the array......
.....
.....