Answers for "searching algorithms in javascript"

1

linear search javascript

function searchAlgorithm (number){
 
    for(let i = 0; i< number; i++){
    if(number == array[i]){
      console.log("Found it, it's at index " + i)
    }else{
      console.log("Not found")
    }
    
  };
  
}


var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

searchAlgorithm(5)
Posted by: Guest on April-17-2020
0

searching algorithms in javascript

// Binary Search is the most efficient algorithm.

function binarySearch(value, list) {
    let first = 0;    //left endpoint
    let last = list.length - 1;   //right endpoint
    let position = -1;
    let found = false;
    let middle;
 
    while (found === false && first <= last) {
        middle = Math.floor((first + last)/2);
        if (list[middle] == value) {
            found = true;
            position = middle;
        } else if (list[middle] > value) {  //if in lower half
            last = middle - 1;
        } else {  //in in upper half
            first = middle + 1;
        }
    }
    return position;
}
Posted by: Guest on July-19-2021

Code answers related to "Javascript"

Browse Popular Code Answers by Language