Project

General

Profile

1 9533 aaronmk
#!/bin/bash -e
2
. "$(dirname "${BASH_SOURCE[0]}")"/util.sh
3
4
if self_not_included; then
5
6
function binsearch() # usage: min=# max=# binsearch >_cmd args... (uses $i)
7 9560 aaronmk
# because integer division truncates, $max is *exclusive*
8 9533 aaronmk
{
9
	echo_func; kw_params min max; : "${min?}" "${max?}"
10 9563 aaronmk
	local min="$min" max="$max" i iter_num=0
11 9533 aaronmk
	while true; do
12 10154 aaronmk
		log- 2 echo_vars iter_num # it will always take log2(max - min) iters
13 9562 aaronmk
14
		i=$(( (min + max)/2 ))
15 10154 aaronmk
		log- 2 echo_vars min max i
16 9533 aaronmk
		if ! (( i > min )); then break; fi
17 9562 aaronmk
		if echo_run "$@"; then min="$i"; else max="$i"; fi
18 9563 aaronmk
19
		((iter_num++)) || true
20 9533 aaronmk
	done
21
	echo "$i"
22
}
23
alias binsearch='"binsearch" ' # last space alias-expands next word
24
25
fi