Javascript Binary Search

| | | | | | |

👻 Check our latest review to choose the best laptop for Machine Learning engineers and Deep learning tasks!

How to code a binary search in JavaScript

Search algorithms greatly facilitate the life of a programmer. This makes it easier to find a particular item in a dataset of tens, hundreds, or thousands of items.

One of the most popular forms of search is binary search. This search quickly finds an element in an array. Each time search examines an item, it halves the number of items to find.

In this guide, we’ll talk about what binary searches are and how they work. Next, we’ll move on to implementing a binary search using two different approaches: iterative and recursive.

Let’s build a binary search algorithm in !

What is a binary search ?

A binary search is a computer algorithm that searches for an element in an ordered array.

Start in the middle of an array and check if the middle element is less, equal or greater than the number you are looking for.

If the number is smaller, the algorithm knows how to keep looking in the left half of the array, where the smaller numbers are ; if the number is greater, the algorithm will focus on the right half of the array. Binary searches only work on ordered lists.

Binary searches are more efficient than linear searches. In fact, each time a search is carried out, the number of items remaining to be found in the list is reduced by half.

How to use a binary search

A binary search is easy to understand a once you’ve learned it.

Before implementing a binary search algorithm, let’s review - take a step. We will find the number " 9 " in a list. Let’s start with an ordered list:

 2 6 8 9 10

First what , we need to find the middle number and assign it to a variable. This is found by calculating the sum of the first and the last number and dividing by two. We will call this "central" variable:

 Start < br> Medium End 2 6 8 9 10

8 is our average number. Thus, we can compare the central number with the one we are looking for. If the central number is the same as the one we are looking for, our search may stop.

In this example, 8 does not equal 9. Our search continues.

So we have to compare if the number in the middle is greater than 9. It is not.

This tells us that the number we are looking for must be after the central number. 9 is greater than 8 in an ordered list. set our starting number to equal the central number. This is because we know that the number we are looking for does not come before the central number.

If the number we are looking for is more baby, we will set the final number to be equal to the middle number. Since the number is smaller than the middle number, we could focus our search on the bottom half of the list.

The binary search repeats again in the top half of the list because 9 is greater than 8:

 Start Medium End 2 6 8 9 10

Let’s find the central number. That’s 9. We can compare 9 with the number we’re looking for. 9 equals the number we are looking for.

This means that our research can stop. We managed to find number 9 on our list!

How to implement a binary search in JavaScript

Binary searches can be implemented using an iterative or recursive approach.

Iterative binary search

An iterative binary search uses a while loop to find an item in a list. This loop will run until the item is found in the list or until the list has been searched.

Let’s start by writing a function that performs our binary search:

Let’s start by defining two variables: start and end. These keep track of the highest and lowest values ‚Äã‚Äãour research is working with. We use a while loop which runs until the start number is greater than the end number. This loop calculates the intermediate number between the start and the end of the list.

If the number we are looking for equals the number in the middle, the number in the middle is returned to our main program. If the number is smaller, the seed value is set to equal the middle number plus 1. These comparisons are made using an if statement .

Otherwise, the final number is set to be the middle number minus one. If our number is not found after executing the while loop, it returns -1. We call it the basic condition. In our main program, we’ll check if the number returned is equal to -1. is, it means our number was not found.

Our function does not work yet. We need to write a main program to name it:

We have defined a list of numbers to search for and the number we want to find in our list. Next, we called the binarySearch function. This will do our research. The search will return -1 or the position of the element we are looking for.

-1 indicates that an item could not be found. If an element is not found, the contents of our ` else ` statement are executed. Otherwise, the contents of the ` if ` statement are executed.

Let’s run our code:

This tells us that our search was successful !

Recursive binary search

A recursive binary search is considered more elegant than an iterative search. This is because binary searches perform the same operation over and over again on a list. This behavior can be implemented using a recursion algorithm.

Open a new JavaScript file and paste this code:

This code does the same comparisons as our first search. Check if the middle number is equal, greater or less than the number we are looking for.

At the start of our function , we used an if statement to check if the starting number is greater than the ending number. If so, it means that our item was not found in the list we specified. In this case, we are returning -1 to the main program.

If the number we are looking for is the same as the central number, the central number is returned to the main program. If the number we are looking for is greater or less than the central number, our binary search function is executed again. This continues until our element is found.

To perform this function, we will need to make a modification to our main program:

We need to pass two more parameters: the values ‚Äã‚Äãof "start" and "end". The value of "start" is equal to 0. The value of "end" is equal to the length of the list minus one.

Let’s run our code and see what happens:

Our binary search was successful ! It uses the same underlying algorithm as the iterative approach. The difference is that the binary search is performed using a function called until the item is found or until the search in the list is complete, whichever comes first.

Conclusion

Binary searches make it easier to find an item in a list. Each time a search is performed, the number of items remaining to be found in a list is reduced by half. This makes a binary search more efficient than a linear search.

You are now ready to implement binary search in JavaScript like an expert!

👻 Read also: what is the best laptop for engineering students?

Javascript Binary Search exp: Questions

How do I merge two dictionaries in a single expression (taking union of dictionaries)?

5 answers

By Carl Meyer

I have two Python dictionaries, and I want to write a single expression that returns these two dictionaries, merged (i.e. taking the union). The `update()` method would be what I need, if it returned its result instead of modifying a dictionary in-place.

``````>>> x = {"a": 1, "b": 2}
>>> y = {"b": 10, "c": 11}
>>> z = x.update(y)
>>> print(z)
None
>>> x
{"a": 1, "b": 10, "c": 11}
``````

How can I get that final merged dictionary in `z`, not `x`?

(To be extra-clear, the last-one-wins conflict-handling of `dict.update()` is what I"m looking for as well.)

5839

Answer #1

How can I merge two Python dictionaries in a single expression?

For dictionaries `x` and `y`, `z` becomes a shallowly-merged dictionary with values from `y` replacing those from `x`.

• In Python 3.9.0 or greater (released 17 October 2020): PEP-584, discussed here, was implemented and provides the simplest method:

``````z = x | y          # NOTE: 3.9+ ONLY
``````
• In Python 3.5 or greater:

``````z = {**x, **y}
``````
• In Python 2, (or 3.4 or lower) write a function:

``````def merge_two_dicts(x, y):
z = x.copy()   # start with keys and values of x
z.update(y)    # modifies z with keys and values of y
return z
``````

and now:

``````z = merge_two_dicts(x, y)
``````

Explanation

Say you have two dictionaries and you want to merge them into a new dictionary without altering the original dictionaries:

``````x = {"a": 1, "b": 2}
y = {"b": 3, "c": 4}
``````

The desired result is to get a new dictionary (`z`) with the values merged, and the second dictionary"s values overwriting those from the first.

``````>>> z
{"a": 1, "b": 3, "c": 4}
``````

A new syntax for this, proposed in PEP 448 and available as of Python 3.5, is

``````z = {**x, **y}
``````

And it is indeed a single expression.

Note that we can merge in with literal notation as well:

``````z = {**x, "foo": 1, "bar": 2, **y}
``````

and now:

``````>>> z
{"a": 1, "b": 3, "foo": 1, "bar": 2, "c": 4}
``````

It is now showing as implemented in the release schedule for 3.5, PEP 478, and it has now made its way into the What"s New in Python 3.5 document.

However, since many organizations are still on Python 2, you may wish to do this in a backward-compatible way. The classically Pythonic way, available in Python 2 and Python 3.0-3.4, is to do this as a two-step process:

``````z = x.copy()
z.update(y) # which returns None since it mutates z
``````

In both approaches, `y` will come second and its values will replace `x`"s values, thus `b` will point to `3` in our final result.

Not yet on Python 3.5, but want a single expression

If you are not yet on Python 3.5 or need to write backward-compatible code, and you want this in a single expression, the most performant while the correct approach is to put it in a function:

``````def merge_two_dicts(x, y):
"""Given two dictionaries, merge them into a new dict as a shallow copy."""
z = x.copy()
z.update(y)
return z
``````

and then you have a single expression:

``````z = merge_two_dicts(x, y)
``````

You can also make a function to merge an arbitrary number of dictionaries, from zero to a very large number:

``````def merge_dicts(*dict_args):
"""
Given any number of dictionaries, shallow copy and merge into a new dict,
precedence goes to key-value pairs in latter dictionaries.
"""
result = {}
for dictionary in dict_args:
result.update(dictionary)
return result
``````

This function will work in Python 2 and 3 for all dictionaries. e.g. given dictionaries `a` to `g`:

``````z = merge_dicts(a, b, c, d, e, f, g)
``````

and key-value pairs in `g` will take precedence over dictionaries `a` to `f`, and so on.

Critiques of Other Answers

Don"t use what you see in the formerly accepted answer:

``````z = dict(x.items() + y.items())
``````

In Python 2, you create two lists in memory for each dict, create a third list in memory with length equal to the length of the first two put together, and then discard all three lists to create the dict. In Python 3, this will fail because you"re adding two `dict_items` objects together, not two lists -

``````>>> c = dict(a.items() + b.items())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: "dict_items" and "dict_items"
``````

and you would have to explicitly create them as lists, e.g. `z = dict(list(x.items()) + list(y.items()))`. This is a waste of resources and computation power.

Similarly, taking the union of `items()` in Python 3 (`viewitems()` in Python 2.7) will also fail when values are unhashable objects (like lists, for example). Even if your values are hashable, since sets are semantically unordered, the behavior is undefined in regards to precedence. So don"t do this:

``````>>> c = dict(a.items() | b.items())
``````

This example demonstrates what happens when values are unhashable:

``````>>> x = {"a": []}
>>> y = {"b": []}
>>> dict(x.items() | y.items())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: "list"
``````

Here"s an example where `y` should have precedence, but instead the value from `x` is retained due to the arbitrary order of sets:

``````>>> x = {"a": 2}
>>> y = {"a": 1}
>>> dict(x.items() | y.items())
{"a": 2}
``````

Another hack you should not use:

``````z = dict(x, **y)
``````

This uses the `dict` constructor and is very fast and memory-efficient (even slightly more so than our two-step process) but unless you know precisely what is happening here (that is, the second dict is being passed as keyword arguments to the dict constructor), it"s difficult to read, it"s not the intended usage, and so it is not Pythonic.

Here"s an example of the usage being remediated in django.

Dictionaries are intended to take hashable keys (e.g. `frozenset`s or tuples), but this method fails in Python 3 when keys are not strings.

``````>>> c = dict(a, **b)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: keyword arguments must be strings
``````

From the mailing list, Guido van Rossum, the creator of the language, wrote:

I am fine with declaring dict({}, **{1:3}) illegal, since after all it is abuse of the ** mechanism.

and

Apparently dict(x, **y) is going around as "cool hack" for "call x.update(y) and return x". Personally, I find it more despicable than cool.

It is my understanding (as well as the understanding of the creator of the language) that the intended usage for `dict(**y)` is for creating dictionaries for readability purposes, e.g.:

``````dict(a=1, b=10, c=11)
``````

instead of

``````{"a": 1, "b": 10, "c": 11}
``````

Response to comments

Despite what Guido says, `dict(x, **y)` is in line with the dict specification, which btw. works for both Python 2 and 3. The fact that this only works for string keys is a direct consequence of how keyword parameters work and not a short-coming of dict. Nor is using the ** operator in this place an abuse of the mechanism, in fact, ** was designed precisely to pass dictionaries as keywords.

Again, it doesn"t work for 3 when keys are not strings. The implicit calling contract is that namespaces take ordinary dictionaries, while users must only pass keyword arguments that are strings. All other callables enforced it. `dict` broke this consistency in Python 2:

``````>>> foo(**{("a", "b"): None})
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: foo() keywords must be strings
>>> dict(**{("a", "b"): None})
{("a", "b"): None}
``````

This inconsistency was bad given other implementations of Python (PyPy, Jython, IronPython). Thus it was fixed in Python 3, as this usage could be a breaking change.

I submit to you that it is malicious incompetence to intentionally write code that only works in one version of a language or that only works given certain arbitrary constraints.

More comments:

`dict(x.items() + y.items())` is still the most readable solution for Python 2. Readability counts.

My response: `merge_two_dicts(x, y)` actually seems much clearer to me, if we"re actually concerned about readability. And it is not forward compatible, as Python 2 is increasingly deprecated.

`{**x, **y}` does not seem to handle nested dictionaries. the contents of nested keys are simply overwritten, not merged [...] I ended up being burnt by these answers that do not merge recursively and I was surprised no one mentioned it. In my interpretation of the word "merging" these answers describe "updating one dict with another", and not merging.

Yes. I must refer you back to the question, which is asking for a shallow merge of two dictionaries, with the first"s values being overwritten by the second"s - in a single expression.

Assuming two dictionaries of dictionaries, one might recursively merge them in a single function, but you should be careful not to modify the dictionaries from either source, and the surest way to avoid that is to make a copy when assigning values. As keys must be hashable and are usually therefore immutable, it is pointless to copy them:

``````from copy import deepcopy

def dict_of_dicts_merge(x, y):
z = {}
overlapping_keys = x.keys() & y.keys()
for key in overlapping_keys:
z[key] = dict_of_dicts_merge(x[key], y[key])
for key in x.keys() - overlapping_keys:
z[key] = deepcopy(x[key])
for key in y.keys() - overlapping_keys:
z[key] = deepcopy(y[key])
return z
``````

Usage:

``````>>> x = {"a":{1:{}}, "b": {2:{}}}
>>> y = {"b":{10:{}}, "c": {11:{}}}
>>> dict_of_dicts_merge(x, y)
{"b": {2: {}, 10: {}}, "a": {1: {}}, "c": {11: {}}}
``````

Coming up with contingencies for other value types is far beyond the scope of this question, so I will point you at my answer to the canonical question on a "Dictionaries of dictionaries merge".

Less Performant But Correct Ad-hocs

These approaches are less performant, but they will provide correct behavior. They will be much less performant than `copy` and `update` or the new unpacking because they iterate through each key-value pair at a higher level of abstraction, but they do respect the order of precedence (latter dictionaries have precedence)

You can also chain the dictionaries manually inside a dict comprehension:

``````{k: v for d in dicts for k, v in d.items()} # iteritems in Python 2.7
``````

or in Python 2.6 (and perhaps as early as 2.4 when generator expressions were introduced):

``````dict((k, v) for d in dicts for k, v in d.items()) # iteritems in Python 2
``````

`itertools.chain` will chain the iterators over the key-value pairs in the correct order:

``````from itertools import chain
z = dict(chain(x.items(), y.items())) # iteritems in Python 2
``````

Performance Analysis

I"m only going to do the performance analysis of the usages known to behave correctly. (Self-contained so you can copy and paste yourself.)

``````from timeit import repeat
from itertools import chain

x = dict.fromkeys("abcdefg")
y = dict.fromkeys("efghijk")

def merge_two_dicts(x, y):
z = x.copy()
z.update(y)
return z

min(repeat(lambda: {**x, **y}))
min(repeat(lambda: merge_two_dicts(x, y)))
min(repeat(lambda: {k: v for d in (x, y) for k, v in d.items()}))
min(repeat(lambda: dict(chain(x.items(), y.items()))))
min(repeat(lambda: dict(item for d in (x, y) for item in d.items())))
``````

In Python 3.8.1, NixOS:

``````>>> min(repeat(lambda: {**x, **y}))
1.0804965235292912
>>> min(repeat(lambda: merge_two_dicts(x, y)))
1.636518670246005
>>> min(repeat(lambda: {k: v for d in (x, y) for k, v in d.items()}))
3.1779992282390594
>>> min(repeat(lambda: dict(chain(x.items(), y.items()))))
2.740647904574871
>>> min(repeat(lambda: dict(item for d in (x, y) for item in d.items())))
4.266070580109954
``````
``````\$ uname -a
Linux nixos 4.19.113 #1-NixOS SMP Wed Mar 25 07:06:15 UTC 2020 x86_64 GNU/Linux
``````

Resources on Dictionaries

5839

Answer #2

In your case, what you can do is:

``````z = dict(list(x.items()) + list(y.items()))
``````

This will, as you want it, put the final dict in `z`, and make the value for key `b` be properly overridden by the second (`y`) dict"s value:

``````>>> x = {"a":1, "b": 2}
>>> y = {"b":10, "c": 11}
>>> z = dict(list(x.items()) + list(y.items()))
>>> z
{"a": 1, "c": 11, "b": 10}

``````

If you use Python 2, you can even remove the `list()` calls. To create z:

``````>>> z = dict(x.items() + y.items())
>>> z
{"a": 1, "c": 11, "b": 10}
``````

If you use Python version 3.9.0a4 or greater, then you can directly use:

``````x = {"a":1, "b": 2}
y = {"b":10, "c": 11}
z = x | y
print(z)
``````
``````{"a": 1, "c": 11, "b": 10}
``````

5839

Answer #3

An alternative:

``````z = x.copy()
z.update(y)
``````

Finding the index of an item in a list

5 answers

Given a list `["foo", "bar", "baz"]` and an item in the list `"bar"`, how do I get its index (`1`) in Python?

3740

Answer #1

``````>>> ["foo", "bar", "baz"].index("bar")
1
``````

Reference: Data Structures > More on Lists

Caveats follow

Note that while this is perhaps the cleanest way to answer the question as asked, `index` is a rather weak component of the `list` API, and I can"t remember the last time I used it in anger. It"s been pointed out to me in the comments that because this answer is heavily referenced, it should be made more complete. Some caveats about `list.index` follow. It is probably worth initially taking a look at the documentation for it:

``````list.index(x[, start[, end]])
``````

Return zero-based index in the list of the first item whose value is equal to x. Raises a `ValueError` if there is no such item.

The optional arguments start and end are interpreted as in the slice notation and are used to limit the search to a particular subsequence of the list. The returned index is computed relative to the beginning of the full sequence rather than the start argument.

Linear time-complexity in list length

An `index` call checks every element of the list in order, until it finds a match. If your list is long, and you don"t know roughly where in the list it occurs, this search could become a bottleneck. In that case, you should consider a different data structure. Note that if you know roughly where to find the match, you can give `index` a hint. For instance, in this snippet, `l.index(999_999, 999_990, 1_000_000)` is roughly five orders of magnitude faster than straight `l.index(999_999)`, because the former only has to search 10 entries, while the latter searches a million:

``````>>> import timeit
>>> timeit.timeit("l.index(999_999)", setup="l = list(range(0, 1_000_000))", number=1000)
9.356267921015387
>>> timeit.timeit("l.index(999_999, 999_990, 1_000_000)", setup="l = list(range(0, 1_000_000))", number=1000)
0.0004404920036904514

``````

Only returns the index of the first match to its argument

A call to `index` searches through the list in order until it finds a match, and stops there. If you expect to need indices of more matches, you should use a list comprehension, or generator expression.

``````>>> [1, 1].index(1)
0
>>> [i for i, e in enumerate([1, 2, 1]) if e == 1]
[0, 2]
>>> g = (i for i, e in enumerate([1, 2, 1]) if e == 1)
>>> next(g)
0
>>> next(g)
2
``````

Most places where I once would have used `index`, I now use a list comprehension or generator expression because they"re more generalizable. So if you"re considering reaching for `index`, take a look at these excellent Python features.

Throws if element not present in list

A call to `index` results in a `ValueError` if the item"s not present.

``````>>> [1, 1].index(2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: 2 is not in list
``````

If the item might not be present in the list, you should either

1. Check for it first with `item in my_list` (clean, readable approach), or
2. Wrap the `index` call in a `try/except` block which catches `ValueError` (probably faster, at least when the list to search is long, and the item is usually present.)

3740

Answer #2

One thing that is really helpful in learning Python is to use the interactive help function:

``````>>> help(["foo", "bar", "baz"])
Help on list object:

class list(object)
...

|
|  index(...)
|      L.index(value, [start, [stop]]) -> integer -- return first index of value
|
``````

which will often lead you to the method you are looking for.

3740

Answer #3

The majority of answers explain how to find a single index, but their methods do not return multiple indexes if the item is in the list multiple times. Use `enumerate()`:

``````for i, j in enumerate(["foo", "bar", "baz"]):
if j == "bar":
print(i)
``````

The `index()` function only returns the first occurrence, while `enumerate()` returns all occurrences.

As a list comprehension:

``````[i for i, j in enumerate(["foo", "bar", "baz"]) if j == "bar"]
``````

Here"s also another small solution with `itertools.count()` (which is pretty much the same approach as enumerate):

``````from itertools import izip as zip, count # izip for maximum efficiency
[i for i, j in zip(count(), ["foo", "bar", "baz"]) if j == "bar"]
``````

This is more efficient for larger lists than using `enumerate()`:

``````\$ python -m timeit -s "from itertools import izip as zip, count" "[i for i, j in zip(count(), ["foo", "bar", "baz"]*500) if j == "bar"]"
10000 loops, best of 3: 174 usec per loop
\$ python -m timeit "[i for i, j in enumerate(["foo", "bar", "baz"]*500) if j == "bar"]"
10000 loops, best of 3: 196 usec per loop
``````

We hope this article has helped you to resolve the problem. Apart from Javascript Binary Search, check other exp-related topics.

Want to excel in Python? See our review of the best Python online courses 2022. If you are interested in Data Science, check also how to learn programming in R.

By the way, this material is also available in other languages:

Carlo OConnell

Moscow | 2022-12-10

Thanks for explaining! I was stuck with Javascript Binary Search for some hours, finally got it done 🤗. I just hope that will not emerge anymore

Julia Porretti

Warsaw | 2022-12-10

Maybe there are another answers? What Javascript Binary Search exactly means?. I am just not quite sure it is the best method

Carlo Williams

Boston | 2022-12-10

Maybe there are another answers? What Javascript Binary Search exactly means?. Will use it in my bachelor thesis

Shop

Learn programming in R: courses

\$

Best Python online courses for 2022

\$

Best laptop for Fortnite

\$

Best laptop for Excel

\$

Best laptop for Solidworks

\$

Best laptop for Roblox

\$

Best computer for crypto mining

\$

Best laptop for Sims 4

\$

Latest questions

NUMPYNUMPY

Common xlabel/ylabel for matplotlib subplots

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

12 answers

NUMPYNUMPY

Flake8: Ignore specific warning for entire file

12 answers

NUMPYNUMPY

glob exclude pattern

12 answers

NUMPYNUMPY

How to avoid HTTP error 429 (Too Many Requests) python

12 answers

NUMPYNUMPY

Python CSV error: line contains NULL byte

12 answers

NUMPYNUMPY

csv.Error: iterator should return strings, not bytes

12 answers

Wiki

Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python

How to specify multiple return types using type-hints

Printing words vertically in Python

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries

Python add suffix / add prefix to strings in a list

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Python - Move item to the end of the list

Python - Print list vertically