Sub topic 12
Binary search on sorted data
This chapter covers the search_mode values 2 and -2, which make XLOOKUP use a binary search. You should already be comfortable with the six XLOOKUP arguments, with match_mode values 0, -1 and 1, and with absolute references such as $E$2. You also need Excel for Microsoft 365, Excel 2021 or later, or Excel for the web.
How XLOOKUP normally searches
By default XLOOKUP uses search_mode 1. It checks the first cell of the lookup array, then the second, and so on until it finds a match or runs out of cells. This is a linear search. A list of 1,000,000 rows may need up to 1,000,000 comparisons for a single lookup.
A binary search takes a different approach and requires the lookup array to be sorted. It compares the lookup value with the middle item. That one comparison shows which half can contain the answer, so the other half is discarded. The search repeats on the remaining half until it finds the item or the range is empty.
Binary search by hand
Take this sorted list and look up 60.
| Position | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
|---|---|---|---|---|---|---|---|
| Value | 10 | 20 | 30 | 40 | 50 | 60 | 70 |
- The middle item is position 4 (40). Since 60 is greater than 40, positions 1 to 4 are discarded.
- The remaining range is positions 5 to 7. Its middle item is position 6 (60), which matches.
That took two comparisons. A linear search would have taken six.
The speed gain
The number of comparisons in a binary search grows with the base-2 logarithm of the list length. Doubling the list adds only one comparison.
| Rows in lookup array | Maximum comparisons, binary search | Maximum comparisons, linear search |
|---|---|---|
| 1,000 | 10 | 1,000 |
| 1,000,000 | 20 | 1,000,000 |
| 1,000,000,000 | 30 | 1,000,000,000 |
Binary search matters when you have many lookup formulas against a large table. For example, 50,000 formulas that each search 500,000 rows can slow a workbook noticeably. For a lookup list of a few hundred rows, you will not see a difference.
The syntax
The search_mode argument is the sixth argument of XLOOKUP:
| search_mode | Behavior | Required order of the lookup array |
|---|---|---|
| 1 | Linear, first to last (default) | Any |
| -1 | Linear, last to first | Any |
| 2 | Binary search | Ascending |
| -2 | Binary search | Descending |
Here is the exact-match case on an ascending list of IDs:
=XLOOKUP(E2, A2:A1000, B2:B1000, "Not found", 0, 2)The following formula is the one from the spine. It combines binary search with match_mode -1, so it returns the entry for the next smaller value when there is no exact match:
=XLOOKUP(E2, A2:A1000, B2:B1000, "Not found", -1, 2)Binary search also works for banded lookups, such as the grade table from the approximate-match chapter. If you store the bounds from highest to lowest (90, 80, 70, 60, 0), use search_mode -2:
=XLOOKUP(B2, $E$2:$E$6, $F$2:$F$6, "Below minimum", -1, -2)Use 2 when the lookup array runs from smallest to largest, and -2 when it runs from largest to smallest. The direction must match the data, because Excel does not detect the order for you.
What happens when the data is not sorted
A binary search assumes the list is sorted. It never examines most cells, so it cannot notice that the assumption is wrong. If the data is out of order, XLOOKUP can discard the half that contains the answer.
Take this unsorted list of seven values: 30, 10, 50, 20, 70, 40, 60. Now look up 30 with search_mode 2.
- The middle item (position 4) is 20. Since 30 is greater, the search keeps positions 5 to 7.
- The middle of those three items is 40. Since 30 is smaller, the search keeps position 5 (70).
- 70 is greater than 30, and nothing is left on the lower side.
The result is #N/A, although 30 is in the first cell. The same list with search_mode 1 finds it immediately.
Worse, an unsorted list does not always fail. Some lookups succeed by luck and others fail, so the formula can look correct during testing and then break when the data changes. When combined with if_not_found, a failed binary search shows your "Not found" message, which hides the real problem.
Checking that a list is sorted
This formula counts the pairs of neighboring cells that are out of ascending order. A result of 0 means the list is sorted ascending:
=SUMPRODUCT(--(A3:A1000 < A2:A999))For a descending list, flip the comparison:
=SUMPRODUCT(--(A3:A1000 > A2:A999))Place the check next to the lookup table, perhaps with conditional formatting that turns red when the count is not 0. The check assumes there are no blank cells inside the range. Blanks compare as zero or empty text, so they can produce false results.
Sorting rules that affect the result
Excel's sort order and the binary search order must agree. Keep these points in mind:
- Mixed types: In an ascending sort, Excel places numbers before text. A numeric-looking ID stored as text and a true number are different types. If a list mixes both, the binary search can fail even when the list looks sorted. This is the same data-type pitfall covered in the errors chapter.
- Case: Text comparison ignores case, so "ab" and "AB" are equal for sorting and matching purposes.
- Duplicates: If the lookup column contains the same value more than once, a binary search returns one of them. You cannot rely on it being the first or the last. If you need the first or last occurrence, use
search_mode1 or -1. - Wildcards: Do not combine
match_mode2 (wildcards) withsearch_mode2 or -2. Wildcard patterns such as*do not follow the sort order, so the results are unreliable.
Choosing a search mode
| Situation | Suggested search_mode |
|---|---|
| Small or unsorted list, exact match | 1 (default) |
| You need the most recent of several matches | -1 |
| Large list, sorted ascending, many lookups | 2 |
| Large list, sorted descending, many lookups | -2 |
| Banded lookup (grades, tax rates, commission tiers) | 2 or -2 if the bounds are sorted, because band tables are naturally sorted |
| Wildcard matching | 1 or -1 only |
| List that other people edit freely | 1, unless you add a sort check |
Microsoft 365 also caches some lookup ranges internally, so an ordinary linear exact-match lookup is often faster than the arithmetic above suggests. If performance is your reason for switching, time the workbook with each setting before you commit. A saving is worth having only if you can measure it, and binary search adds a risk that a linear search does not have.
Worked example: a large price list
A price table has 200,000 product codes in A2:A200001, sorted ascending, with unit prices in B2:B200001. An order sheet has the product code to find in E2.
- Check that the list is sorted:
=SUMPRODUCT(--(A3:A200001 < A2:A200000))- When the result is 0, use the binary search lookup:
=XLOOKUP(E2, $A$2:$A$200001, $B$2:$B$200001, "Unknown product", 0, 2)- If someone later adds new products at the bottom without re-sorting, the check returns a number greater than 0 and the lookups become unreliable. Re-sort the table, or change
search_modeback to 1.
Keeping the table in an Excel Table and sorting it from the Data tab helps, but new rows still have to be placed in sorted order.
Summary
search_mode2 and -2 use a binary search that halves the remaining range at every step.- The lookup array must be sorted ascending for 2 and descending for -2.
- Unsorted data can give
#N/Aor wrong values without any warning. - Binary search suits large sorted tables and many lookups. For small or frequently edited lists, the default is safer.
- With duplicates, a binary search does not guarantee which matching row you get.
Exercise
A sorted-ascending list in A2:A5000 holds employee IDs and B2:B5000 holds names. Write an XLOOKUP formula that finds the ID in E2 using a binary search and returns the text "No such ID" when it is missing. Then write a formula that counts out-of-order neighbors in the ID list.
Show answer
Lookup: =XLOOKUP(E2, A2:A5000, B2:B5000, "No such ID", 0, 2). Sort check: =SUMPRODUCT(--(A3:A5000 < A2:A4999)). A result of 0 means the list is sorted ascending.
Exercise
A tax table has bounds in E2:E6 sorted from highest to lowest (500000, 250000, 100000, 50000, 0) and rates in F2:F6. Write a formula that returns the rate for the income in B2 using the largest bound that is less than or equal to the income, with a binary search. What would go wrong if you used search_mode 2 here?
Show answer
=XLOOKUP(B2, $E$2:$E$6, $F$2:$F$6, "Below minimum", -1, -2). Search_mode 2 expects an ascending list, but the bounds are descending. The search could discard the half that contains the right band and return #N/A or a wrong rate, with no warning.