Linear Search Algorithm in Java

1. Introduction

Linear search, also known as sequential search, is one of the simplest search algorithms. It works by iterating through the data set, comparing each element with the target value until a match is found or the end of the data set is reached.

2. Implementation Steps

1. Start from the leftmost element of the array.

2. Compare the target element with the current array element.

3. If the target element matches, return the index.

4. If the target element doesn't match, move to the next element and repeat step 2.

5. If the end of the array is reached without finding the target, return an indicator that the element is not present.

3. Implementation in Java

public class LinearSearch {
    // Method to search a given element in the array
    public static int search(int arr[], int x) {
        int n = arr.length;
        for (int i = 0; i < n; i++) {
            if (arr[i] == x) {
                return i; // Element found, return its index
            }
        }
        return -1; // Element not found
    }
    public static void main(String[] args) {
        int arr[] = { 2, 4, 1, 7, 5, 3 };
        int x = 7;
        int result = search(arr, x);
        if (result == -1) {
            System.out.println("Element not present in the array");
        } else {
            System.out.println("Element is present at index: " + result);
        }
    }
}

Output:

Element is present at index: 3

Explanation:

1. The algorithm begins by checking the leftmost element of the array.

2. It compares the current element with the target value (in this case, the value 7).

3. If the target value matches with the current element, the index of that element is returned.

4. If a match is not found, the algorithm moves on to the next element and repeats the process.

5. If the algorithm reaches the end of the array without finding a match, it returns -1 indicating that the target element is not present in the array.


Comments