...

/

Understanding Bisectors

Understanding Bisectors

A bisector will allow us to locate where to insert an element in an array.

We'll cover the following...

We are going to need to figure out where to display the tooltip. At the moment, we know where the reader is hovering their mouse. However, we do not know where to display the tooltip. We do not even know which point the reader wants to view. The only information we have at our disposal is the x and y-coordinates of the mouse.

We are going to use a bisector to help us figure out where to display the tooltip. A bisector is a function that allows us to locate where to insert an element into an array in order to maintain a sorted array. Before we discuss how a bisector will help us, let’s look at an example of how a bisector works.

Bisector example

Let’s say we had an array of five numbers. The numbers in this array range from 10 to 50.

Press + to interact
const numbers = [10, 20, 30, 40, 50]
numbers.push(35)
// New Array: 10, 20, 30, 40, 50, 35

We may want to push a new number into the array. For example, we may want to push the number 35 into the array. One solution would be to call the push() function. The number would get inserted onto the end of the array. JavaScript will create a new array with our number inserted at the end.

This solution works, but it leaves our array unsorted. The number 35 should be between 30 and 40. We can fix this problem by sorting the array.

But there is ...