0

Working on this assignment.

Write a Bash script, insert-sort.sh, which sorts a list of command line parameters in ascending order. For example, your command will look something like: $ insert-sort.sh 7 2 3 9 -1 and type enter. Your program will return: -1 2 3 7 9

This is what I have so far

array=();
for param in "$@"; do
    if [ -z "$array" ]; then
        array[0]="$param";     
    else
        array[param]="$param";
    fi
done
echo ${array[@]} 

The problem when I try to test the script, I get inconsistent answer. Sorted when it is not supposed to.

For example, if I run '/././BASH/insert-sort.sh' 1 3 2 I get 1 2 3

if I run '/././BASH/insert-sort.sh' 4 2 3 I get 4 2 3

1 Answer 1

1

The first parameter isn't being sorted correctly. You're always assigning it to index 0, regardless of its value. Every other $param goes into the param'th slot.

Sign up to request clarification or add additional context in comments.

2 Comments

Yes, I know. But 3 2 gets sorted to 2 3 in first and not in second attempt. Thanks for reply btw.
"There is nothing in this script that sorts at all." With JohnKugelman's fix, yes, the code does sort. That is the way bash arrays work. (It won't work on negative numbers, though.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.