0
0
DSA Typescriptprogramming~3 mins

Why Linear Search Algorithm in DSA Typescript?

Choose your learning style9 modes available
The Big Idea

What if you could find anything in a messy pile without sorting it first?

The Scenario

Imagine you have a messy drawer full of different colored socks. You want to find a red sock, but you have no idea where it is. So, you start pulling out socks one by one from the top until you find the red one.

The Problem

Searching like this by hand is slow and tiring. If the red sock is at the bottom, you waste time checking every single sock. You might also lose track or miss the sock if you get distracted.

The Solution

The linear search algorithm works just like checking each sock one by one, but it does it quickly and without mistakes. It goes through each item in a list until it finds the one you want or reaches the end.

Before vs After
Before
let socks = ['blue', 'green', 'yellow', 'red', 'black'];
for (let i = 0; i < socks.length; i++) {
  if (socks[i] === 'red') {
    console.log('Found red sock at position', i);
    break;
  }
}
After
function linearSearch(items: string[], target: string): number {
  for (let index = 0; index < items.length; index++) {
    if (items[index] === target) {
      return index;
    }
  }
  return -1;
}

const position = linearSearch(['blue', 'green', 'yellow', 'red', 'black'], 'red');
console.log('Found red sock at position', position);
What It Enables

Linear search lets you quickly find any item in a list without needing it to be sorted or organized.

Real Life Example

When you look for a contact name in your phone's unsorted list, your phone uses a linear search to find the name by checking each contact one by one.

Key Takeaways

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

It works on any list, sorted or not.

It is simple but can be slow for very large lists.