Sort numbers using arrays in Shell Script

By: Vivek G  

This shell script demonstrates the use of arrays with a script that sorts 5 numbers and prints the sorted numbers.
#
# Declare the array of 5 subscripts to hold 5 numbers
#
declare nos[5]=(4 -1 2 66 10)

#
# Prints the number befor sorting
#
echo "Original Numbers in array:"
for (( i = 0; i <= 4; i++ ))
do
  echo ${nos[$i]}
done

#
# Now do the Sorting of numbers
#

for (( i = 0; i <= 4 ; i++ ))
do
   for (( j = $i; j <= 4; j++ ))
   do
      if [ ${nos[$i]} -gt ${nos[$j]}  ]; then
           t=${nos[$i]}
           nos[$i]=${nos[$j]}
           nos[$j]=$t
      fi
   done
done

#
# Print the sorted number
# 
echo -e "\nSorted Numbers in Ascending Order:"
for (( i=0; i <= 4; i++ )) 
do
  echo ${nos[$i]}
done



Archived Comments

1. blank
View Tutorial          By: veera venkata satya naga maha veera ambika trimurthulu at 2015-04-20 06:32:54

2. hahaha
View Tutorial          By: seshu babu at 2015-04-20 06:29:14

3. This will give the output check it out

nos=( 2 4 1 30 23 )
echo "Original

View Tutorial          By: shruthi at 2013-01-18 06:00:08

4. does not work.

output:
./number2: line 4: nos[5]: cannot assign list to array

View Tutorial          By: praveen at 2012-08-30 19:04:20

5. hii
i have

two varirables

var=4 5 6......n
var1=3 4 5...

View Tutorial          By: niranjan at 2012-07-31 06:47:36

6. hii
i have

two varirables

var=4 5 6......n
var1=3 4 5...

View Tutorial          By: niranjan at 2012-07-31 06:45:46

7. its very nice
View Tutorial          By: keerthi at 2012-06-28 17:04:36

8. how to declare Array ?? in LINUX
i m try this same code 4 run but that's not work
and<

View Tutorial          By: Chand at 2012-03-18 06:47:09

9. thanks ...
View Tutorial          By: Dipesh at 2011-09-07 17:05:21


Most Viewed Articles (in Linux )

Latest Articles (in Linux)

smskannel SMS gateway run in background

Running jar files in background in ssh window

Can't locate ExtUtils/MakeMaker.pm in @INC ...

Could not open '': No such file or directory at lib/ExtUtils/MM_Unix.pm line 2697

make: Nothing to be done for `all'.

bash: svn: command not found

apxs: command not found

bash: make: command not found

How to burn your CD / DVD ISO image using Nero Burning ROM (Ahead Software) on Windows

How to burn your CD / DVD ISO image using Media Creator (Adaptec/Roxio) on Windows

How to burn your CD / DVD ISO image using Nero Express (Ahead Software) on Windows

How to burn your CD / DVD ISO image using NISO Recorder V2 Power Toy on Windows

Compiling and Installing software from source in Linux

Installing using Debian apt-get in Linux

How to burn your CD / DVD ISO image using k3b on CentOS

Comment on this tutorial