Bash Script for Bubble Sort - Simple Sorting Example
for ((i=0; i arr[j+1] )); then temp=${arr[j]}; arr[j]=${arr[j+1]}; arr[j+1]=$temp; fi; done; done .Examples
How to Think About It
Algorithm
Code
#!/bin/bash
arr=($@)
n=${#arr[@]}
for ((i=0; i<n-1; i++)); do
for ((j=0; j<n-i-1; j++)); do
if (( arr[j] > arr[j+1] )); then
temp=${arr[j]}
arr[j]=${arr[j+1]}
arr[j+1]=$temp
fi
done
done
echo "Sorted array: ${arr[*]}"Dry Run
Let's trace sorting the array [3, 1, 2] through the bubble sort code.
Initial array
arr = [3, 1, 2]
First pass comparisons and swaps
Compare 3 and 1: swap -> arr = [1, 3, 2] Compare 3 and 2: swap -> arr = [1, 2, 3]
Second pass
Compare 1 and 2: no swap Compare 2 and 3: no swap No swaps, sorting done.
| Pass | Array State |
|---|---|
| 1 | 1 3 2 |
| 1 | 1 2 3 |
| 2 | 1 2 3 |
Why This Works
Step 1: Compare adjacent elements
The code uses if (( arr[j] > arr[j+1] )) to check if two neighbors are out of order.
Step 2: Swap elements
If the first is greater, it swaps them using a temporary variable to reorder the array.
Step 3: Repeat passes
The nested loops repeat this process, pushing the largest unsorted element to the end each pass.
Alternative Approaches
#!/bin/bash
arr=($@)
n=${#arr[@]}
swapped=1
while (( swapped )); do
swapped=0
for ((i=0; i<n-1; i++)); do
if (( arr[i] > arr[i+1] )); then
temp=${arr[i]}
arr[i]=${arr[i+1]}
arr[i+1]=$temp
swapped=1
fi
done
done
echo "Sorted array: ${arr[*]}"#!/bin/bash arr=($@) sorted=($(printf "%s\n" "${arr[@]}" | sort -n)) echo "Sorted array: ${sorted[*]}"
Complexity: O(n^2) time, O(1) space
Time Complexity
Bubble sort uses nested loops over the array, resulting in O(n^2) time because each element is compared multiple times.
Space Complexity
It sorts the array in place, so it only needs O(1) extra space for temporary swaps.
Which Approach is Fastest?
Using a swap flag to stop early can improve average performance, but external sort commands are faster for large data.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Basic Bubble Sort | O(n^2) | O(1) | Small arrays, learning |
| Bubble Sort with Swap Flag | O(n) best, O(n^2) worst | O(1) | Nearly sorted arrays |
| External sort command | O(n log n) | O(n) | Large arrays, practical use |