Created
April 4, 2024 17:09
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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