Nekode
Data structure and algorithm

Searching algorithm

Learn basic binary & Sequential searching algorithm

Rifki ahmad fahrezi

Rifki ahmad fahrezi

Binary search is an algorithm that searches through a sorted array. Binary search does not iterate through every element of the array. Instead, it divides the search space in half at each step.

Implementation

Now we're going to implement the binary search algorithm by making a function to do the operation using javascript. Here is the function's code:

const binarySearch = (arr, target) => {
    let low = 0
    let high = arr.length - 1
 
    while (low <= high) {
        let mid = Math.floor((low + high) / 2)
        
        if (arr[mid] === target) {
            return mid // Found the target, return index
        } else if (arr[mid] < target) {
            low = mid + 1 // Search in the right half
        } else {
            high = mid - 1 // Search in the left half
        }
    }
    
    return -1 // Target not found
}

Explanation

  1. Initialize pointers
    • low (start of the array)
    • high (end of the array)
  2. Loop until low exceeds high:
    • Find mid = Math.floor((low + high) / 2)
    • If arr[mid] === target, return mid
    • If target is greater than arr[mid], search the right half (low = mid + 1)
    • If target is smaller than arr[mid], search the left half (high = mid - 1)
  3. Return -1 if not found.

Sequential (or linear) search is an algorithm that checks each element of an array one by one sequentialy. It is useful for searching in unsorted arrays.

Implementation

Now we're going to implement the Sequential search algorithm by making a function to do the operation using javascript. Here is the function's code:

const array = [12, 43, 435, 56, 7867, 78]
 
const sequentialSearch = (arr, target) => {
    for (let i = 0 i < arr.length i++) {
        if (arr[i] === target) {
            return i // Return index if found
        }
    }
    return -1 // Target not found
}
 
console.log(sequentialSearch(array, 56)) // => 3

Explanation

  1. Define the function: -The function sequentialSearch takes two parameters: an array and a target value.
  2. Loop through the array:
    • Iterate over each element.
    • If an element matches the target, return its index.
  3. Return -1 if the target is not found.

Addition

Binary search is works only for sorted array and fast for larger datasets.
Sequential search is works for any array but slower for large datasets

On this page