https://www.youtube.com/watch?v=PUv66718DII
binarySearch('g', ["a", "b", "c", "d"]);
// -> lo = 0 | 3 | 5
// -> h = 5 | 5 | 5
// -> m = 2 | 4 | 5
// -> value = 'c' | 'e' | 'f'
binarySearch('g', ["a", "b", "c", "d"], echo);
function binarySearch(key, array, echo=recho.identity) {
let lo = echo.watch(0);
let hi = echo.watch(array.length - 1);
while (lo <= hi) {
const mi = echo.watch(Math.floor((lo + hi) / 2));
const value = echo.watch(array[mi]);
if (value < key) lo = mi + 1;
else if (value > key) hi = mi - 1;
else return mi;
}
return -1;
}
Transpile to:
function binarySearch(key, array, echo=recho.identity) {
let lo = echo.watch(0, 'lo');
let hi = echo.watch(array.length - 1, 'hi');
while (lo <= hi) {
const mi = echo.watch(Math.floor((lo.val + hi.val) / 2), 'mi');
const value = echo.watch(array[mi], 'value');
if (value < key) lo.val = mi.val + 1;
else if (value > key) hi.val = mi.val - 1;
else return mi;
}
return -1;
}
Transpile to: