Binary search in JavaScript. A practical example

コメント · 304 ビュー

What is Binary Search?

If you have an array that you need to search, the easiest way might be to use indexOf() or maybe a for() loop. Each option will start on the left side of the field and iterate through each item in the field until the desired value is found.

Now compare this to binary search.

 

Binary search allows you to search a sorted array by repeatedly splitting the array in half.

 

Binary search works by checking whether our search value is greater than, less than, or equal to the median value in our array:

 

If it is less than, we can remove the right half of the field.

If it is more than, we can remove the left half of the field.

If equal, we return the value

The catch is that the array must be sorted - ie the values ​​must be for the binary search to work.

 

When working with large chunks of data, auto binary signals it is much faster to use binary search because you remove 1/2 of the wrong values ​​of the array in each iteration instead of just one wrong value.

 

Project.

I recently published an article on how I created an interactive 30-day Bitcoin price chart with React and the API.

 

One of the most important aspects of a chart is the tooltip, which displays relevant data when you hover over it. As you move the mouse, the graph updates with data from the nearest data point. Here is an example gif:



How does it work?

 

I have an array of all data point coordinates. The coordinates are inside the object and each object has an svgX key. It looks something like this:

 

svgData = [

  {svgX: 1367,844, data...},

  {svgX: 1684,478, data...},

  {svgX: 1168,474, data...},

  {svgX: 1344,854, data...},

  // etc.

]

I originally used a simple for loop to compare the current mouse X position to all the svgX values ​​in my dataset.

 

For a loop.

 

This is what the for loop code looks like. Any object has an svgX value that is closest to the X mouse location - that's the data we want to highlight.

コメント