Searching Algorithm :: Linear Search & Binary Search

Searching Algorithm :: Linear Search & Binary Search

I'm gonna list several searching algorithm, its pseudocode and the real code with javascript.

Linear Search Pseudocode

  • This function accepts array and a value

  • Loop through the array and check if the current array elements is equal to value.

  • If it is, return the element in which the element is found.

  • If the value is never found, return -1

function linearSearch(arr, val) {
    for(var i = 0; i < arr.length; i++) {
        if(arr[i] === val) return i;
    }
    return -1;
}

linearSearch([1,2,4,9,6], 9); // 3

Linear Search Big O

O(1) Best

O(n) Average

O(n) Worst


Binary Search Pseudocode

  • This function accepts a sorted array and value.

  • Create a left pointer at the start of the array, and a right pointer at the end of the array.

  • While the left pointer comes before the right pointer: Create a pointer in the middle, If you find the value you want return index, If the value is too small, move the left pointer up, If the value is too large, move the right pointer down

  • If you never find the value, return -1.

function binarySearch(arr, elem) {
    var start = 0;
    var end = arr.length - 1;
    var middle = Math.floor((start + end) / 2);
    while ( array[middle] !== elem && start <= end ) {
        if(elem < arr[middle]) end = middle - 1;
        else start = middle + 1;
        middle = Math.floor((start + end) / 2);
    }
    return array[middle] === elem ? middle : -1;
}

binarySearch([2,4,5,7,11,15,90], 7) // 3

Big O notation

O(log n ) : worst & average case

O(1) : Best case