📄 Need a professional CV? Try our Resume Builder! Get Started

Watch the Video Explanation

For a more detailed explanation of Binary Search, watch this video where I walk you through the concept and implementation in-depth:

What is Linear Search?

Definition: Linear Search is a simple searching algorithm that traverses through each element of an array sequentially to find the target element.

Use Case: It's effective for small data sets or unsorted arrays where other algorithms like binary search are not feasible.

Algorithm Steps:

  • Start at the first element of the array.
  • Compare the current element with the target.
  • If a match is found, return the index.
  • If the loop completes without a match, return -1 (element not found).

Python Code:

def linear_search(arr, target):
    for i in range(len(arr)):
        if arr[i] == target:
            return i  # Element found, return index
    return -1  # Element not found

# Example Usage
arr = [10, 20, 30, 40, 50]
target = 30
result = linear_search(arr, target)

if result != -1:
    print(f"Element found at index {result}")
else:
    print("Element not found")

Test Case:

Input:
arr = [10, 20, 30, 40, 50]
target = 30

Output:
Element found at index 2

Linear Search: Finding 30 in Array

Current Element
Target (30)
Elements Already Checked

Initial Array

010
120
230
340
450
Start: Checking arr[0] = 10

Step 1: Check 10

010check
120
230
340
450
arr[0] = 10 is not equal to 30, moving to next element.

Step 2: Check 20

010
120check
230
340
450
arr[1] = 20 is not equal to 30, moving to next element.

Step 3: Check 30

010
120
230found!
340
450
arr[2] = 30 is equal to 30, target found at index 2!

Algorithm Summary

  • Time Complexity: O(n)
  • Space Complexity: O(1)
  • Does not require sorted array
  • Checks each element sequentially until the target is found

Time Complexity:

  • Best Case: O(1), when the target is the first element.
  • Worst Case: O(n), when the target is the last element or not found.
  • Average Case: O(n).

Nandi Vardhan
Data Scientist, content creator, and passionate educator in the field of machine learning and data science.