简体   繁体   中英

Bubble sort bash script

I am trying to sort a list of names and their scores in dictionary order in bash using bubble sort. The arrays are

Ted 86
Anthony 70
Mark 95
Kyle 65
David 75

The names are stored in an array names, and the scores are in an array scores

This is my code and its giving me an error on line 30 saying "to many arguments" and I cannot seem to find why.

#! /bin/bash
inputfile="$1"

if [[ !(-f "$1") ]]; then
    echo "$1 must be a file"
    exit 1
else
    echo "$1 is a file"
fi

names=()
scores=()

while IFS= read -r name score
do
    names+=( "$name" )
    scores+=( "$score" )
done < $inputfile
echo "The arrays before sorting"

for (( i=0; i<${#names[@]}; ++i ))
do
    echo "${names[$i]} ${scores[$i]}"
done

echo "The sorted arrays using bubble sort"
for (( i = 0; i < ${#names[@]}; i++ ))
do
    for (( j = $i; j < ${#names[@]}; j++ ))
    do
            if [ ${names[$i]} -gt ${names[$j]} ]; then #error here
                    t=${names[$i]}
                    names[$i]=${names[$j]}
                    names[$j]=$t
            fi
    done
done

for (( i=o; i<${#names[@]}; ++i ))
do
    echo "${names[$i]}"
done

Could someone copy and paste to see if they get the same issue?

while IFS= read -r name score

is wrong. With IFS= no words are not splitted - the whole line is assigned to name and score is always empty.

I cannot seem to find why.

Because you pass multiple arguments to [ , it expands to for ex i=0 j=1 :

# if [ ${names[$i]} -gt ${names[$j]} ]
# expands to:
if [ Ted 86 -gt Anthony 70 ]

No [ program receives 6 arguments and doesn't know what to do with them - so it exits with an error. When you fix the IFS problem mentioned above - still you are comparing names as numbers with -gt - I guess you meant to sort people by their scores not by their names.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM