Skip to content

Instantly share code, notes, and snippets.

@ncalm
Created April 4, 2024 17:09
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ncalm/5bbf7177fc6177c23883a41da5dd9790 to your computer and use it in GitHub Desktop.
Save ncalm/5bbf7177fc6177c23883a41da5dd9790 to your computer and use it in GitHub Desktop.
This Excel LAMBDA function enables simulation and visualization of the binary search algorithm to find a value in a sorted array.
IFOMITTED = LAMBDA(arg, then, IF(ISOMITTED(arg), then, arg));
BINARYSEARCH = LAMBDA(search_for, array, [stop], [iter], [left_index], [right_index],
LET(
_iter, IFOMITTED(iter, 1),
_stop, IFOMITTED(stop, ROWS(array)+1),
_left_index, IFOMITTED(left_index, 1),
_right_index, IFOMITTED(right_index, ROWS(array)),
_seq, SEQUENCE(ROWS(array)),
_left_value, INDEX(array, _left_index, 1),
_right_value, INDEX(array, _right_index, 1),
_mid_index, FLOOR.MATH((_left_index + _right_index) / 2),
_direction, SIGN(INDEX(array, _mid_index, 1) - search_for),
output, IF((_seq<=_right_index)*(_seq>=_left_index), array, #N/A),
error_array, EXPAND({#N/A},ROWS(array),,#N/A),
pointer, LAMBDA(arg, IF(_seq=arg,INDEX(array,arg,1)+6,#N/A)),
result, IF(_direction=0,HSTACK(IF(array=INDEX(array, _mid_index, 1), array, #N/A),error_array, error_array),
IF(_direction=1,BINARYSEARCH(search_for, array, _stop, _iter+1, _left_index, _mid_index-1),
IF(_direction=-1,BINARYSEARCH(search_for, array, _stop, _iter+1, _mid_index+1, _right_index),
"Not found"))),
IF(_iter=stop,
HSTACK(output, pointer(_left_index), pointer(_right_index)),
result)
)
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment