Bash Script to Find Smallest Element in Array
smallest=${array[0]}; for i in "${array[@]}"; do if (( i < smallest )); then smallest=$i; fi; done; echo $smallest.Examples
How to Think About It
Algorithm
Code
array=(3 1 4 1 5) smallest=${array[0]} for i in "${array[@]}"; do if (( i < smallest )); then smallest=$i fi done echo "$smallest"
Dry Run
Let's trace array=(3 1 4 1 5) through the code
Initialize smallest
smallest=3 (first element)
Compare with 3
3 < 3? No, smallest stays 3
Compare with 1
1 < 3? Yes, smallest=1
Compare with 4
4 < 1? No, smallest stays 1
Compare with 1
1 < 1? No, smallest stays 1
Compare with 5
5 < 1? No, smallest stays 1
| Element | Smallest So Far |
|---|---|
| 3 | 3 |
| 1 | 1 |
| 4 | 1 |
| 1 | 1 |
| 5 | 1 |
Why This Works
Step 1: Start with first element
We set smallest to the first element because we need a starting point to compare others.
Step 2: Loop through array
We check each element using a for loop to compare it with the current smallest.
Step 3: Update smallest if needed
If an element is less than smallest, we update smallest to that element.
Step 4: Print the result
After the loop ends, smallest holds the smallest element, which we print.
Alternative Approaches
array=(3 1 4 1 5) echo "${array[@]}" | tr ' ' '\n' | sort -n | head -1
array=(3 1 4 1 5) smallest=${array[0]} i=1 while [ $i -lt ${#array[@]} ]; do if (( array[i] < smallest )); then smallest=${array[i]} fi ((i++)) done echo "$smallest"
Complexity: O(n) time, O(1) space
Time Complexity
The script checks each element once, so time grows linearly with array size.
Space Complexity
Only a few variables are used, so space stays constant regardless of array size.
Which Approach is Fastest?
The loop method is fastest for large arrays because it avoids external commands like sort.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Loop with comparison | O(n) | O(1) | Large arrays, efficient |
| Sort and pick first | O(n log n) | O(n) | Small arrays, simple code |
| While loop with index | O(n) | O(1) | Manual control, similar to loop |