What is the best case practice(implementation) for array element search in js?

const nums = [2, 48, 15 , 19 , 21, 50... ... ... n];

*Solution 1*
function numsSearch(searchNum, arry){
    return arry.includes(searchNum);
}
*Solution 2*
function numsSearch2(searchNum, arry){
    for(let i=0; i<arry.length; i++)
       if(arry[i] === searchNum)
         return true;
    return false;
}
*Solution 3*
function numsSearch3(searchNum, arry){
   for (let key of arry)
       if (key === searchNum)
         return true;
   return false;
}
*Solution 4*
function numsSearch4(arr, target) {
    let leftIndex = 0;
    let rightIndex = arr.length - 1;

    while (leftIndex <= rightIndex) {
        let middleIndex = Math.floor((leftIndex + rightIndex) / 2);
        if(target === arr[middleIndex]) {
            return middleIndex;
        }
        if(target < arr[middleIndex]) {
            rightIndex = middleIndex - 1;
        } else {
            leftIndex = middleIndex + 1;
        }
    }
    return false;
}

Solutions 1 through 3 probably have the same time complexity: O(n). The last one is an attempt at binary search which requires the array to be sorted, but the array you mentioned specifically is not sorted (due to the 48). That would have O(log(N)) complexity if the input were already sorted.

In terms of readability, solution 1 is the most readable and probably makes the function completely unnecessary since you could just as easily call the includes method directly (and is probably just as readable in the calling code if not more readable). Solution 3 is the next best followed by solution 2 and finally solution 4. Of course, it is a bit unfair to compare solution 4 to the others since it is actually trying to implement a searching algorithm whereas the others are just linear searches.

Hope that answers whatever you wanted to know.

2 Likes

I should probably also mention that the binary search algorithm is broken since you should be modifying the rightIndex (not the leftIndex) when the target is less than the one at middleIndex. See this helpful visualization of the binary search algorithm.

I also think it was meant to return true rather than middleIndex since the alternative returns false.

2 Likes

Thank you for the link
:orange_heart: