Display a sorted array

How do I create a function ("sortarr") that takes a parameter of array and returns a sorted array?

Shell script

echo "Original Numbers in array:"
for (( i = 0; i <= 4; i++ ))
do echo ${nos[$i]}
done
2

2 Answers

You don't. You use sort:

$ echo ${array[@]}
1 8 14 -4 123 12
$ printf '%s\n' "${array[@]}" | sort -n
-4
1
8
12
14
123

And to make it a function:

mysort(){ printf '%s\n' "$@" | sort -n
}
array=(1 8 14 -4 123 12)
mysort "${array[@]}"

If you really, really want to, you can try and implement a sorting algorithm in bash. It might be simpler to just hit your head a few times against the wall instead though. You really don't want to be writing that sort of thing in a shell language. Still, if you insist, you could use something like this (reimplemented in bash from one of the examples here):

mysort(){ for((i=${#array[@]}-1;i>=0; i--)); do for((j=1;j<=$i; j++)); do if [[ ${array[j-1]} -gt ${array[j]} ]]; then temp="${array[j-1]}" array[j-1]="${array[j]}" array[j]="$temp" fi done done
}
declare -a array=(1 8 14 -4 123 12)
mysort $array
printf '%s\n' "${array[@]}"

Seriously though, do not, I repeat not, try to do any serious computing task in the shell. There are better tools for it. Any half way decent scripting language, for example, will already have methods that let you sort. For instance:

  • Perl

    $ perl -le '@array=(1,8,14,-4,123,12); print join " ", sort @array'
    -4 1 12 123 14 8
  • Python

    $ python -c 'array = [1,8,14,-4,123,12]; array.sort(); print(array)'
    [-4, 1, 8, 12, 14, 123]
2

Just the function :

 Sort(){for item in $@; do echo $item; done | sort}

Code with list making , function and display :

list=( Item3 Item1 Item2 )
Sort() { for item in $@; do echo $item; done | sort }
sorted_list=$(Sort ${list[@]})
echo ${sorted_list[@]}

Quick Walk through :
1. Make the list .
list=()
2. Create a sort function .
Sort(){}
3. Functions first line of code goes through the list and assigns the entry to the variable called item .
for Variable in $@ ;
3. For each list item pass to the echo command .
do echo $item ;
4. When is done the echo command output is piped to the sort command .
done |
5. Thats the function created . After that create a variable for the sorted list .
sorted_list=
6. Fill the variable with the output of the function .
sorted_list=$()
7. Call the function
sorted_list=$(Sort())
8. Pass the list to the function .
sorted_list=$(Sort ${list[@]})
8. Display the sorted list
echo ${sorted_list[@]}

1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like