Suppose you look for a specific numeric parameter n for a program.
It behaves in one way if the parameter is less than n and in another when it is greater than n.
Binary search can be applied.
Examples when you have such a scenario are:
- A web application, and you fill in GET/POST-values with curl or wget
- You use a revision control system and a bug was introduced at some version, and you wrote a test for that bug. (git has a command for that: git-bisect)
Anyway, here a simple binarytest.sh.
It calls the program (third parameter) with a number as parameter.
#!/bin/bash
START=$(($1))
STOP=$(($2))
TEST="$3"
if [ "$START" == "" ] || [ "$STOP" == "" ] || [ "$START" == "$STOP" ] || [ "$TEST" == "" ]; then
echo "SYNAPSIS: $0 <start> <stop> <testprog>"
exit
fi
while [ "$START" != "$STOP" ]; do
N=$(( ($START + $STOP)/2 ))
echo "Testing against $N"
if $TEST $N; then
if [ $(($START-$STOP)) == "-1" ]; then
START="$STOP"
else
START="$N"
fi
echo "selecting upper half: $START:$STOP"
else
if [ $(($START-$STOP)) == "-1" ]; then
STOP="$START"
else
STOP="$N"
fi
echo "selecting lower half: $START:$STOP"
fi
done
Recent Comments