DEV Community

Paolo Ventura
Paolo Ventura

Posted on

100 algos in 100 days (Day 16)

This was a tuesday dedicated to Binary search.

I watched videos and (re)learnt the common iterative implementation of this.

export const iterativeFunction = function (arr, x) {

    let start = 0, end = arr.length - 1;

    // Iterate while start not meets end
    while (start <= end) {
        let mid = Math.floor((start + end) / 2);

        if (arr[mid] === x) return true;

        // Else look in left or right half accordingly
        if (arr[mid] < x)
            start = mid + 1;
        else
            end = mid - 1;
    }

    return false;
}
Enter fullscreen mode Exit fullscreen mode

Then did the practice question on find the rotation point of a partially sorted dictionary.
Learning points being:

  1. Data only needs to be partially sorted to use binary search
  2. If it is not sorted numbers you might have to look for a pattern or compare other indexes that you know. For example, the first and last.

Top comments (0)