Tutorials » Algorithms Tutorial » Linear Search Algorithm

Linear Search Algorithm

Linear search checks each item one by one until it finds the target value.

Table of Contents

What is linear search?

Linear search checks each item one by one until it finds the target value. Algorithms are important for improving problem-solving skills, writing efficient programs, and preparing for coding interviews.

Before studying algorithms, it helps to understand basic programming concepts in Python or JavaScript.

How linear search Works

  1. Start with a list of values.
  2. Compare values against the target.
  3. Continue until the target is found or the search ends.
  4. Return the position or a message that the target was not found.

linear search in Python

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

print(linear_search([4, 2, 8, 6], 8))

linear search in JavaScript

function linearSearch(arr, target) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] === target) return i;
  }
  return -1;
}

console.log(linearSearch([4, 2, 8, 6], 8));

Time Complexity

CaseComplexity
BestO(1)
AverageO(n)
WorstO(n)

To understand performance better, read Time Complexity Explained and Big O Notation.

Common Mistakes

Tip: Practice algorithms in a code editor. See the best code editors and best Python IDEs.

Frequently Asked Questions

Is linear search important?

Yes. It helps programmers solve problems efficiently and understand how code performance changes with input size.

Should beginners learn algorithms?

Yes. Beginners should learn basic searching, sorting, recursion, and Big O notation after learning programming fundamentals.

Which language is best for learning algorithms?

Python is beginner-friendly, while JavaScript is useful for web developers. Both are good for learning algorithms.