Searching Algorithms with javascript
Searching Algorithms
Linear Search
it finds what we are searching for by
brute force, making it easy to implement.
we will use three different ways in javascript.
first way : search with includes method.
*example: Array.includes("something");
*includes method will return True or False.
second way : search with indexOf method.
*example: Array.indexOf("something");
*indexOf method will return number 'the index of the something'
third way : search with Find method.
*example: Array.find(item => item === "something");
*we write in this method a function and it will return something we search about.
Binary Search
Binary search only works on sorted arrays.O(log n) 'big o notation'.
Example : [1,2,3,4,5,6,7,8,9,10] for example if we search for number 7
we have in this array three things the first thing is the left = 1 and second thing is a right = 10 and last thing is a mid = 5
so we will check the number 7 is more than the mid or less than the mid.
if number 7 is more than mid the left will equal to mid + 1
if number 7 less than mid the right will equal to mid - 1
Code :
const binarySearch = (sortedArr, value) => {
let left = 0;
let right = sortedArr.length - 1;
while(left <= right) { const mid = Math.floor((left + right) / 2); const midVal = sortedArr[mid]; if(midVal === value) { return mid; } else if (midVal < value) { left = mid + 1;
} else{
right = mid - 1;
}
}
return -1;
};
تعليقات
إرسال تعليق