Searching algorithms in Javascript

Searching algorithms are used to find a specific element within a collection of data, such as an array or a list. They help locate the position of an item or determine whether it exists in the data structure.

Searching algorithms are used to find a specific element in a collection of data. Some common searching algorithms include:

  • Linear search: This algorithm searches for the element by comparing it to each element in the collection.
  • Binary search: This algorithm searches for the element by dividing the collection in half and then searching the half that contains the element.
  • Hash tables: This algorithm uses a hash function to map each element in the collection to a unique index. The element can then be found by looking up the index in the hash table.

Linear search: This algorithm searches for the element by comparing it to each element in the collection.

function linearSearch(array, element) {
  for (let i = 0; i < array.length; i++) {
    if (array[i] === element) {
      return i;
    }
  }

  return -1;
}

const array = [1, 2, 3, 4, 5];
const index = linearSearch(array, 3);

if (index !== -1) {
  console.log(`The element ${3} was found at index ${index}`);
} else {
  console.log(`The element ${3} was not found in the array`);
}

OUTPUT:

The element 3 was found at index 2
function linearSearch(arr, target) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] === target) {
      return i; // Return the index where the target is found
    }
  }
  return -1; // Return -1 if the target is not found
}

const myArray = [2, 4, 6, 8, 10];
const targetValue = 6;

const result = linearSearch(myArray, targetValue);
if (result !== -1) {
  console.log(`Found ${targetValue} at index ${result}`);
} else {
  console.log(`${targetValue} not found in the array.`);
}

Why Use Linear Search:

  • Linear search is straightforward and easy to implement.
  • It’s suitable for small collections or when the data is not sorted.
  • Linear search is used when you need to find the first occurrence of a target value.

2. Binary Search:

Binary search: This algorithm searches for the element by dividing the collection in half and then searching the half that contains the element.

Binary search is a more efficient searching algorithm, but it requires that the data be sorted. It works by repeatedly dividing the search interval in half until the target element is found or the interval becomes empty.

  1. Example
function binarySearch(arr, target) {
  let left = 0;
  let right = arr.length - 1;

  while (left <= right) {
    const mid = Math.floor((left + right) / 2);

    if (arr[mid] === target) {
      return mid; // Return the index where the target is found
    }

    if (arr[mid] < target) {
      left = mid + 1;
    } else {
      right = mid - 1;
    }
  }

  return -1; // Return -1 if the target is not found
}

const sortedArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const targetValue = 6;

const result = binarySearch(sortedArray, targetValue);
if (result !== -1) {
  console.log(`Found ${targetValue} at index ${result}`);
} else {
  console.log(`${targetValue} not found in the array.`);
}

Why Use Binary Search:

  • Binary search is highly efficient for large sorted collections.
  • It has a time complexity of O(log n), making it much faster than linear search.
  • Binary search is used when you need to search in sorted data.

2. Example

function binarySearch(array, element) {
  let low = 0;
  let high = array.length - 1;

  while (low <= high) {
    const mid = Math.floor((low + high) / 2);

    if (array[mid] === element) {
      return mid;
    } else if (array[mid] > element) {
      high = mid - 1;
    } else {
      low = mid + 1;
    }
  }

  return -1;
}

const array = [1, 2, 3, 4, 5];
const index = binarySearch(array, 3);

if (index !== -1) {
  console.log(`The element ${3} was found at index ${index}`);
} else {
  console.log(`The element ${3} was not found in the array`);
}

Output:

The element 3 was found at index 2

3. Hash tables: This algorithm uses a hash function to map each element in the collection to a unique index. The element can then be found by looking up the index in the hash table.

class HashTable {
  constructor(size) {
    this.table = new Array(size);
  }

  hash(key) {
    return key % this.table.length;
  }

  set(key, value) {
    const index = this.hash(key);
    this.table[index] = value;
  }

  get(key) {
    const index = this.hash(key);
    return this.table[index];
  }
}

const hashTable = new HashTable(10);

hashTable.set("name", "Bard");
hashTable.set("age", 23);

const name = hashTable.get("name");
const age = hashTable.get("age");

console.log(name); // Bard
console.log(age); // 23

Why use searching algorithms in JavaScript?

Searching algorithms are used in JavaScript to find a specific element in a collection of data. This can be useful for a variety of tasks, such as:

  • Finding a specific product in a list of products.
  • Finding a specific user in a database of users.
  • Finding a specific word in a document.
  • Finding a specific file in a directory.
  • Finding a specific node in a graph.

Read More Topics

System Design Syllabus

Introduction to System Design

Architectural Patterns in System Design

Scalability and Performance in System Design

Database Design in System Design

Distributed Systems in System Design

System Integration and APIs in System Design

Cloud Computing in Sestem Design

Containerization and Orchestration in System Design

High Availability and Disaster Recovery

Security in System Design

Performance Tuning and Optimization

Case Studies and Real-World Projects

B.Tech 4 YEAR CS/IT PROJECTS And Placement

Face Detection Project Idea

Weather Forecasting APP in MERN Project

JavaScript Tips and Trick

Arrays in data Structure

All DSA Topics in JavaScript

e-commerce website React.js logic code

JavaScript function that could be used to add a product to the shopping cart

Linked List in JavaScript

Stack in JavaScript

Leave a Comment

Skip to content