I am trying to use binary search to display a grade of a student if they are in the array. There is no issue with my search, however, I am apparently not correctly comparing the data in my conditional statements. The elif
runs no matter what name I enter. There seems to be some problem with at least one of the values that I am comparing.
Here is what is stored in the array:
Ann:A
Bob:C
Cindy:B
Dean:F
Emily:A
Frank:C
Ginger:D
Hal:B
Ivy:A
Justin:F
Karen:D
Here is my script.
#!/bin/bash
# Create array from student list
studentArray=($(cat ./studentList.dat))
# Ask for student name
echo "Enter Student Name"
studentName=$(read)
# variable to store if a student has been found
studentFound="false"
# variable to store student grade
studentGrade=""
# start and end index of the studentArray
START=0
END=$((${#studentArray[@]}-1))
# binary search
while [ "$START" -le "$END" ]; do
MIDDLE=$((START+((END-START)/2)))
middleItem=$(echo ${studentArray[$MIDDLE]} | cut -d: -f1)
if [ "$studentName" = "$middleItem" ]; then
studentFound="true"
studentGrade=$(echo ${studentArray[$MIDDLE]} | cut -d: -f2)
break
elif [[ "$studentName" < "$middleItem" ]]; then
((END=MIDDLE-1))
else
((START=MIDDLE+1))
fi
done
if [ "$studentFound" == "true" ]; then
echo $studentGrade
else
echo "Sorry, there is no student by that name"
fi