Javascript Search Algorithm

Yasin DALKILIÇ
2 min readFeb 21, 2023

--

hello everyone , in this article we will talk about search algorithm in javascript.Search algorithms in JavaScript are used to find an element in an array or object. Here are some of the most commonly used search algorithms:

Linear Search

This algorithm finds the target element by sequentially checking all the elements in an array. It is the simplest search algorithm, but it can be slow for large datasets.

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

const array = [1, 2, 3, 4, 5];
const target = 3;
console.log(linearSearch(array, target)); //

Binary Search

This algorithm is used to find a target element in a sorted array. It divides the array in half and compares to determine if the target element is in the left or right half. It repeats this process until the middle of the array is reached.

function binarySearch(array, target) {
let left = 0;
let right = array.length - 1;
while (left <= right) {
const middle = Math.floor((left + right) / 2);
if (array[middle] === target) {
return middle;
} else if (array[middle] < target) {
left = middle + 1;
} else {
right = middle - 1;
}
}
return -1;
}

const array = [1, 2, 3, 4, 5];
const target = 3;
console.log(binarySearch(array, target)); // 2

Hash Tables

A hash table is a data structure that maps keys to values. It uses a hash function to calculate an index into an array of buckets or slots, from which the desired value can be found. It is a very fast search algorithm with a time complexity of O(1).

const hashTable = {};
hashTable['key1'] = 'value1';
hashTable['key2'] = 'value2';
console.log(hashTable['key1']); // 'value1'

☕ Buy me Coffee : https://buymeacoffee.com/yasindlklcc

My Youtube Channel.

Good work everyone.

--

--

Yasin DALKILIÇ
Yasin DALKILIÇ

Written by Yasin DALKILIÇ

Hi, My name is Yasin I am a Software Developer, I love so much researching and development 😊 Here is my youtube channel @webciyasin

No responses yet