Java From Beginner To Advanced

0% completed

Previous
Next
Linear Search

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.

Problem Statement

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.

Example:

  • Input:

    • Array: [4, 2, 7, 1, 3]
    • Target: 7
  • Output: Target 7 found at index 2.

  • Justification: The target value 7 is present in the array at index 2.

Step-by-Step Algorithm

Implementing Linear Search involves the following steps:

  1. Initialize Variables:

    • Let arr be the array to search through.
    • Let target be the value to search for.
    • Let 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.
  2. Iterate Through the Array:

    • Loop through each element of the array using its index.
    • For each element, check if it matches the target.
  3. Check for Target:

    • If the current element is equal to the target, assign the current index to foundIndex and terminate the loop as the target has been found.
  4. Result:

    • After the loop, check if foundIndex is not -1. If it's not, print the index where the target was found.
    • If foundIndex remains -1, indicate that the target is not present in the array.

Code

Below is the Java code that demonstrates how to perform a linear search on an array of integers.

Java
Java

. . . .

Explanation

  1. Initialization:

    • An integer array arr is initialized with the values {4, 2, 7, 1, 3}.
    • The target value to search for is set to 7.
  2. Calling the linearSearch Method:

    • The linearSearch method is called with arr and target as arguments.
    • The method returns the index of the target if found; otherwise, it returns -1.
  3. Linear Search Process:

    • The method iterates through each element of the array using a for loop.
    • For each element arr[i], it checks if it equals the target.
    • When i = 2, arr[2] is 7, which matches the target.
    • The method returns 2, indicating that the target is found at index 2.
  4. Result Display:

    • Back in the main method, the returned index is checked.
    • Since the index is not -1, it prints that the target 7 is found at index 2.
  5. If Target Not Found:

    • If the target were not present in the array, linearSearch would return -1.
    • The main method would then print that the target is not found in the array.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next