Bash Script to Sort Array in Descending Order
Use
sorted=($(printf "%s\n" "${array[@]}" | sort -nr)) to sort a Bash array in descending order.Examples
Inputarray=(3 1 4 1 5)
Output5 4 3 1 1
Inputarray=(10 20 30 40)
Output40 30 20 10
Inputarray=()
Output
How to Think About It
To sort an array in descending order, first print each element on a new line, then use the
sort -nr command to reverse numeric sort the lines, and finally read the sorted lines back into an array.Algorithm
1
Take the input array.2
Print each element on a separate line.3
Use the sort command with numeric reverse option to sort lines descending.4
Read the sorted lines back into a new array.5
Print or use the sorted array as needed.Code
bash
array=(3 1 4 1 5) sorted=($(printf "%s\n" "${array[@]}" | sort -nr)) echo "${sorted[@]}"
Output
5 4 3 1 1
Dry Run
Let's trace sorting array=(3 1 4 1 5) through the code
1
Print array elements
3\n1\n4\n1\n5
2
Sort lines in reverse numeric order
5\n4\n3\n1\n1
3
Read sorted lines into array
sorted=(5 4 3 1 1)
| Iteration | Value |
|---|---|
| 1 | 3 |
| 2 | 1 |
| 3 | 4 |
| 4 | 1 |
| 5 | 5 |
Why This Works
Step 1: Print each element on a new line
Using printf "%s\n" prints each array element on its own line so sort can process them.
Step 2: Sort with reverse numeric option
The sort -nr command sorts lines in descending numeric order.
Step 3: Read sorted lines back into array
Command substitution $(...) captures sorted lines and stores them as array elements.
Alternative Approaches
Using a loop and manual comparison
bash
array=(3 1 4 1 5) for ((i=0; i<${#array[@]}; i++)); do for ((j=i+1; j<${#array[@]}; j++)); do if (( array[i] < array[j] )); then temp=${array[i]} array[i]=${array[j]} array[j]=$temp fi done done echo "${array[@]}"
This manual bubble sort approach works but is slower and more complex than using <code>sort</code>.
Using <code>sort -nr</code> for numeric sort
bash
array=(3 1 4 1 5) sorted=($(printf "%s\n" "${array[@]}" | sort -nr)) echo "${sorted[@]}"
Use <code>-n</code> with <code>sort</code> for numeric sorting to handle numbers correctly.
Complexity: O(n log n) time, O(n) space
Time Complexity
The sorting step dominates with O(n log n) time because sort uses efficient algorithms like mergesort or quicksort.
Space Complexity
Extra space is needed to hold the sorted output array, so space complexity is O(n).
Which Approach is Fastest?
Using sort is faster and simpler than manual sorting loops, especially for large arrays.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Using sort -nr | O(n log n) | O(n) | Numeric arrays needing correct numeric order |
| Manual nested loops | O(n^2) | O(1) | Small arrays or learning sorting logic |
| Using sort -r | O(n log n) | O(n) | Simple and fast for most cases with string data |
Use
sort -nr to sort numbers correctly in descending order.Forgetting to use
printf to print array elements line by line before sorting.