Write a bash script to do a binary search. Read student names and grades from a file into an array. Prompt the user for a student name. Find the name in the array and displa
I think it's best to use a generic binary search function then to code your own for your particular case.
# Returns the largest i for which `command i` succeeds (exits with a null exit code)
function dichotomic_search {
min=$1
max=$2
command=$3
while [ $min -lt $max ]; do
# Compute the mean between min and max, rounded up to the superior unit
current=`expr '(' "$min" + "$max" + 1 ')' / 2`
if $command $current
then min=$current
else max=`expr $current - 1`
fi
done
echo $min
}
It calls the function given as its last argument repetitively using binary search to find the last value for which it returns true. More explanations on Github
In your case, you would use it like that:
#!/usr/bin/env bash
source dichotomic.sh
arr=(Ann:C Bob:A Cindy:B Dean:E Emily:A Karen:A Zob:A)
function is_smaller {
element=$(echo ${arr[$2]} | cut -f1 -d :)
if [[ "$element" > "$1" ]]
then false
else true
fi
}
read target
highest_index=`expr ${#arr[@]} - 1`
index=$(dichotomic_search 0 $highest_index "is_smaller $target")
echo "${arr[$index]}"