searching algorithms in javascript

Solutions on MaxInterview for searching algorithms in javascript by the best coders in the world

showing results for - "searching algorithms in javascript"
Jonah
28 Jun 2018
1function searchAlgorithm (number){
2 
3    for(let i = 0; i< number; i++){
4    if(number == array[i]){
5      console.log("Found it, it's at index " + i)
6    }else{
7      console.log("Not found")
8    }
9    
10  };
11  
12}
13
14
15var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
16
17searchAlgorithm(5)
Sophie
26 Jan 2020
1// Binary Search is the most efficient algorithm.
2
3function binarySearch(value, list) {
4    let first = 0;    //left endpoint
5    let last = list.length - 1;   //right endpoint
6    let position = -1;
7    let found = false;
8    let middle;
9 
10    while (found === false && first <= last) {
11        middle = Math.floor((first + last)/2);
12        if (list[middle] == value) {
13            found = true;
14            position = middle;
15        } else if (list[middle] > value) {  //if in lower half
16            last = middle - 1;
17        } else//in in upper half
18            first = middle + 1;
19        }
20    }
21    return position;
22}
23