1

I have some numbers, and I want to print those numbers in ascending and descending order using a for loop. Please find the example for loop only which I am providing.

  1. Ascending order.

    for i in 10 -29 33 67 -6 7 -10; do
        echo ("Printing the numbers in ascending order: $i")
    done
    
  2. descending order.

    for i in 10 -29 33 67 -6 7 -10; do
        echo ("Printing the numbers in descending order: $i")
    done
    
Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
Harish
  • 29
  • 1
  • 7
  • You can look here https://stackoverflow.com/questions/7442417/how-to-sort-an-array-in-bash – Mert Köklü Nov 26 '19 at 13:19
  • To sort numbers you need to "see" them all at the same time. So it's not possible to do it "in a loop" - you need to load all the numbers, sort them, and then output. – KamilCuk Nov 26 '19 at 13:29

2 Answers2

1

You can use a bubble algorithm to sort an array :

Descending order

numbers=(10 -29 33 67 -6 7 -10)

for (( i=0 ; i < ${#numbers[@]}; i++ )) 
do
    for (( j=0 ; j < ${#numbers[@]}; j++ )) 
    do
      if [[ ${numbers[$j]} -lt  ${numbers[$i]} ]]
      then
        tmp=${numbers[$i]}
        numbers[$i]=${numbers[$j]}
        numbers[$j]=${tmp}
      fi
    done
done

for n in "${numbers[@]}"
do
    echo "$n"
done

Ascending order

numbers=(10 -29 33 67 -6 7 -10)

for (( i=0 ; i < ${#numbers[@]}; i++ )) 
do
    for (( j=0 ; j < ${#numbers[@]}; j++ )) 
    do
      if [[ ${numbers[$j]} -gt  ${numbers[$i]} ]]
      then
        tmp=${numbers[$i]}
        numbers[$i]=${numbers[$j]}
        numbers[$j]=${tmp}
      fi
    done
done

for n in "${numbers[@]}"
do
    echo "$n"
done

Or you can cheat and use sort :

Descending order

for i in $( echo "10 -29 33 67 -6 7 -10" | tr ' ' '\n' | sort -nr )
do
  echo $i
done

Ascending order

for i in $( echo "10 -29 33 67 -6 7 -10" | tr ' ' '\n' | sort -r )
do
  echo $i
done

Hope it helps!

Matias Barrios
  • 4,674
  • 3
  • 22
  • 49
0

Well, this approach doesn't seem to be fair, but it works.

#!/bin/bash

touch list.txt
for i in 29 -12 3 44; do
  echo $i >> list.txt
done

while read LINE; do
  echo $LINE
done < <(sort -n list.txt)
rm list.txt
Konstantin
  • 133
  • 1
  • 8
  • 1
    Instead of using a temporary file, you could redirect the entire loop: `for i in 29 -12 3 44; do echo "$i"; done | sort -n` – Benjamin W. Nov 26 '19 at 14:27