New Tool Radar

AI for Data & Spreadsheets

How to Check Whether an AI-Written Lookup Using Binary Search Runs on Unsorted Data

Check whether an AI-written lookup that uses binary search runs on unsorted data and returns an invalid result.

Schematic with three steps: Read the search mode in the formula; Check whether the lookup column is sorted; Switch to a linear search and re-test.

XLOOKUP’s search mode 2 and MATCH with match type 2 or -1 use binary search, which is fast but only valid on sorted data: ascending for mode 2, descending for mode -2. On unsorted data, binary search jumps to the middle, assumes the order, and can return a wrong row or report that a present value is missing. An AI-written lookup that chooses binary search for speed needs sorted data, or it needs the default linear search instead.

What you need

  • The AI-written lookup formula and its search or match mode
  • The lookup column, with its sort order checked
  • One known lookup value and the answer it should return

Step 1: Read the search mode in the formula

Click the formula cell and read the last argument. In XLOOKUP, search mode 2 means ascending binary search and -2 means descending; in MATCH, type 1 needs ascending data and -1 needs descending data.

Step 2: Check whether the lookup column is sorted that way

Sort a copy of the lookup column and compare it with the original order. If the orders differ, the data is not sorted for the binary search the formula uses.

Step 3: Switch to a linear search and re-test

Change the search mode to 1, the default linear search, or sort the data first, and test with the known value. The result must now be the correct row.

Worked example: synthetic product codes in entry order

The table below is a synthetic example. It shows the expected result of checking an AI-written binary search lookup; no formula was run.

Check Value Result
Lookup value tested P-118 Present in the table
Search mode as written 2 Ascending binary search
Result as written Wrong row Data is unsorted
Search mode 1 result 65 Correct price for P-118

Expected result (UNTESTED). XLOOKUP with search mode 2 on unsorted product codes returns the wrong row for P-118, because binary search assumes ascending data; switching to search mode 1 returns 65, the correct price. This check was not run live; the table shows the expected result for the synthetic example.

Limits

  • Binary search on unsorted data returns invalid results without any error, so the failure is silent.
  • MATCH with type 0 is an exact linear search and works on unsorted data; only types 1 and -1 need sorted data.
  • Sorting the data to fix the search changes the order of the source, so sort a copy when the order matters.
  • XLOOKUP’s default search mode is 1, a linear search from the first item, which is safe on unsorted data.

Sources

See all