⚡ JavaScript

Algorithmes de recherche en JavaScript (Node.js) : guide détaillé

What is it and why? (a real-life analogy)

Imagine you lost your favorite LEGO brick in a huge box of parts. You can:

  • Go through all the parts in order — slow, but you'll definitely find it.
  • Look only at the red parts, if your brick is red — faster.
  • Divide the box into sections and search in each one — even faster.
  • Look in a special catalog that records where each part is located — instantly.

It's the same in programming. A search algorithm is a way to find the desired element in a data array. We use search every day:

  • When we look for a contact in our phone
  • When we Google something
  • When we search for a file on our computer
  • When we check if an item is in stock in an online store
💡 Important: Search algorithms are the foundation of any program's operation. Without them, databases, search engines, social networks, and even your favorite games would not work.

Theory: how it works from the inside

Let's figure out what kinds of search algorithms exist and how they differ.

Linear Search

The simplest way: we go through the array from beginning to end and check each element. It's like going through all the books on a shelf to find the one you need.

  • Pros: works with any data, even if it's not sorted
  • Cons: slow for large arrays
  • Complexity: O(n) — time increases proportionally to the number of elements

Binary Search

A clever way: we divide the sorted array in half and see which half the target element could be in. It's like looking for a word in a dictionary — you open it roughly in the middle and see which direction to go.

  • Pros: very fast for large sorted arrays
  • Cons: the data must be sorted
  • Complexity: O(log n) — time increases very slowly

Depth-First Search (DFS) and Breadth-First Search (BFS)

These algorithms are used for searching in complex data structures — graphs and trees. For example, when you need to find a path in a maze or check if two people are connected in a social network.

Hash Tables

The fastest search method. We store data in a special structure where each element has a unique key. It's like a coat check at a theater — you hand over a ticket and get your coat instantly.

  • Complexity: O(1) — instant, regardless of size
⚠️ Remember: There is no perfect algorithm for all cases. The choice depends on what kind of data you have and what you want to do.

Syntax in JavaScript (Node.js): all forms and variants

In JavaScript, there are several ways to implement search. Let's look at each one.

Built-in Array Methods

Method What it does Returns
indexOf() Searches for an element in an array The index of the element or -1
find() Searches for the first element that matches a condition The element or undefined
findIndex() Searches for the index of the first matching element The index or -1
includes() Checks if an element exists in the array true or false
filter() Finds all matching elements A new array

Custom Algorithm Implementations

Sometimes you need to write the algorithm yourself — for understanding or for special cases.

Code examples — from simple to complex

Example 1: Linear search using indexOf()

// The simplest way to find an element in an array
const fruits = ['apple', 'banana', 'orange', 'pear', 'kiwi'];

// Check if the array contains an orange
const orangeIndex = fruits.indexOf('orange');

// indexOf returns the index of the element or -1 if the element is not found
if (orangeIndex !== -1) {
    console.log(`Orange found at position ${orangeIndex}`);
} else {
    console.log('Orange not found');
}

// Result: Orange found at position 2

Example 2: Linear search from scratch

// Let's write our own linear search function
function linearSearch(arr, target) {
    // Go through all elements of the array
    for (let i = 0; i < arr.length; i++) {
        // If we found the target element
        if (arr[i] === target) {
            return i; // Return its index
        }
    }
    return -1; // If nothing was found
}

// Test our function
const numbers = [10, 20, 30, 40, 50, 60, 70];
const result = linearSearch(numbers, 40);
console.log(`Number 40 found at index: ${result}`); // 3

const notFound = linearSearch(numbers, 100);
console.log(`Number 100 found at index: ${notFound}`); // -1

Example 3: Binary search (recursive)

// Binary search — works only with sorted arrays!
function binarySearchRecursive(arr, target, left = 0, right = arr.length - 1) {
    // Base case: if the left boundary is greater than the right — element not found
    if (left > right) {
        return -1;
    }

    // Find the middle of the array
    const mid = Math.floor((left + right) / 2);

    // If the element in the middle is what we're looking for
    if (arr[mid] === target) {
        return mid; // Return its index
    }

    // If the target is smaller than the middle element, search the left half
    if (target < arr[mid]) {
        return binarySearchRecursive(arr, target, left, mid - 1);
    }

    // Otherwise, search the right half
    return binarySearchRecursive(arr, target, mid + 1, right);
}

// Test our function
const sortedNumbers = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100];
const searchResult = binarySearchRecursive(sortedNumbers, 70);
console.log(`Number 70 found at index: ${searchResult}`); // 6

const notFoundResult = binarySearchRecursive(sortedNumbers, 55);
console.log(`Number 55 found at index: ${notFoundResult}`); // -1