Refactor a Linear Search into a Binary Search with JavaScript

InstructorTyler Clark

Share this video with your friends

Send Tweet

Binary search is an algorithm that accepts a sorted list and returns a search element from the list. It provides a dramatic performance boost over searching linearly through a list for an element. Let’s play around number of iterations required for each search method to complete and refactor our linear list search into a binary search function.

Paweł Waszczyński
~ 5 years ago

What tool to write code are you using?

Nick Luo
~ 5 years ago

In your CodeSandBox editor, you forgot to sort the array, so i don't think it works properly with Binary Search.

In your tutorial, if you need to sort the array first, "Let's begin to refactor our function. First thing we'll do is sort our items from lowest to greatest.", then perform binary search, this will be slower than just do a linear search of the item in the list.

So i think it's better to seperate into 2 sections, 1 section talk about search on unsorted list, the other section talk about binary search and we are given a sorted list of items.

tsvika
~ 5 years ago

Thing is, if you sort the array, your looping the whole thing to begin with...

Eleonora Lester
~ 4 years ago

Shouldn't you actually have to "get rid" of the parts of the array that are bigger / lower ? What I mean is... shouldn't you have to assign mid to low or high depending on the case?

Something like:

 if(item > midValue) { 
            low = mid 
            high --;
        }
        else {
            high = mid;
            low ++;
        }
~ 4 months ago

What would be the big O notation if we use indexOf ?