我必须编写一个bash脚本,用户从学生和成绩列表中输入名称,然后显示该名称和成绩。这是一个二进制搜索,我必须首先对列表进行排序,并且必须使用中间点来检查名称。我写了这段代码,但是无论我输入什么名字,它都只会显示相同的成绩,如果名称不在列表中,它将显示姓名和固定成绩。
sort -o sorted.dat sort.dat
((count = 0))
while read names[$count]; do
((count++))
done<sorted.dat
# Store the names and grades into arrays
names=( $( cut -d: -f1 name.txt ) )
grades=( $( cut -d: -f2 name.txt ) )
# Prompt user for a name
echo "Type the student's name (use proper capitalization!), followed by [ENTER]:"
# Read the user's response
read names
length=${#names[@]}
start=0
end=$((length - 1))
match=0
while [[ $start -le $end ]]; do
middle=$((start + ((end - start)/2)))
middle_name=${names[$middle]}
if [[ $middle_name -gt $name ]]; then
end=$((middle-1))
echo "${name}'s grade is a(n): ${grades[$name]}."
elif [[ $middle_name -lt $name ]]; then
start=$((middle+1))
echo "${name}'s grade is a(n): ${grades[$name]}."
else
# A match was found
match=1
echo "${name}'s grade is a(n): ${grades[$middle_name]}."
break
fi
done
# Check if a match was found
if [[ $match = 0 ]]; then
echo "Couldn't find that student..."
fi