Step-by-Step Guide to Linear Search Algorithm

Bhavesh SharmaBhavesh Sharma
2 min read

Note:

“I recently started learning about searching algorithms and began with the simplest one—linear search.”

Introduction

  • Searching is the process of finding a specific value or item in a collection of data.

  • In programming, searching is used to check whether a value exists in a list, array, database, or any other data structure.

  • For example, if you have a list of student names and want to check if "Dev" is in the list, you need a search algorithm to do that.

  • Searching is one of the most basic and important operations in computer science because it's used in almost every application—like finding a contact in your phone or a product on a shopping site.

  • There are different types of searching algorithms. The simplest one is Linear Search, and more advanced ones include Binary Search, Hashing, etc.

“Linear search is a method of finding a value in a list by checking each element one by one from the beginning until the value is found or the list ends.” It’s like flipping through pages of a book one by one to find a specific word. Simple.

Example:

public class Main {
    public static void main(String[] args) {
        int[] arr = {2, 1, 3, 4, 5, 6};
        int ans = searchTarget(arr,1);
        System.out.println("At Index: " + ans);
    }    
    static int searchTarget(int[] arr, int target) {
        int element = 0;
        if (arr.length == 0) {
            return -1;
        }
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] == target) {
                return i;
            }
        }
        return -1;
    }
}
//Output = At Index: 1

In this we are Searching an Element in an Array names arr.

How Linear Search Works

  • Walk through the steps:

    1. Start from the first element.

    2. Compare it with the target value.

    3. If it matches, return the index.

    4. If not, move to the next.

    5. Repeat until the end.

    6. Simple

  • Small or unsorted data.

  • Quick solutions or prototypes

  • Not efficient for large datasets.

Time Complexity

  • Talk briefly about Big O notation:

    • Worst case: O(n)

    • Best case: O(1)

    • Average case: O(n)

What’s Next ?

Other Types of Searching For Sure Like:

Binary Search, and 2d Searches.

Thats all for Today will write asap.

Peace ✌️.

0
Subscribe to my newsletter

Read articles from Bhavesh Sharma directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Bhavesh Sharma
Bhavesh Sharma

i am currently starts to learning new things as you can check my progress in blogs.