Bash Script for Selection Sort with Example and Explanation
for ((i=0; i. Examples
How to Think About It
Algorithm
Code
arr=(3 1 2 5 4) n=${#arr[@]} for ((i=0; i<n-1; i++)); do min=$i for ((j=i+1; j<n; j++)); do if (( arr[j] < arr[min] )); then min=$j fi done temp=${arr[i]} arr[i]=${arr[min]} arr[min]=$temp done printf "%s " "${arr[@]}"
Dry Run
Let's trace the array [3, 1, 2] through the selection sort code.
Initial array
arr = [3, 1, 2]
First outer loop (i=0)
min = 0 (value 3), check j=1 (1 < 3) → min=1, check j=2 (2 < 1) no, swap arr[0] and arr[1] → arr = [1, 3, 2]
Second outer loop (i=1)
min = 1 (value 3), check j=2 (2 < 3) → min=2, swap arr[1] and arr[2] → arr = [1, 2, 3]
| Iteration | Array State |
|---|---|
| Start | [3, 1, 2] |
| i=0 | [1, 3, 2] |
| i=1 | [1, 2, 3] |
Why This Works
Step 1: Find minimum in unsorted part
The inner loop uses if (( arr[j] < arr[min] )) to find the smallest element from the unsorted section.
Step 2: Swap minimum with current
After finding the minimum, the script swaps it with the element at the current position using temporary storage.
Step 3: Repeat until sorted
The outer loop moves forward, shrinking the unsorted section until the entire array is sorted.
Alternative Approaches
arr=(3 1 2 5 4) 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 printf "%s " "${arr[@]}"
arr=(3 1 2 5 4) IFS=$'\n' sorted=($(sort -n <<<"${arr[*]}")) printf "%s " "${sorted[@]}"
Complexity: O(n^2) time, O(1) space
Time Complexity
Selection sort uses two nested loops each running up to n times, resulting in O(n^2) time.
Space Complexity
It sorts the array in place, so it only needs O(1) extra space for swapping.
Which Approach is Fastest?
Using the built-in sort command is fastest for large data, while selection sort is simple but slower.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Selection Sort | O(n^2) | O(1) | Small arrays, learning sorting logic |
| Bubble Sort | O(n^2) | O(1) | Simple swaps, educational use |
| sort command | O(n log n) | O(n) | Large arrays, practical sorting |