Prerequisites
Sample Data
The script will sort the following array of integers:
data=(29 10 14 37 13)
DID YOU KNOW?
Selection Sort is one of the simplest sorting algorithms but is inefficient for large datasets due to its O(n^2)
time complexity.
The Script
This Bash script implements the Selection Sort algorithm:
#!/bin/bash
# Sample data
data=(29 10 14 37 13)
# Selection Sort implementation
n=${#data[@]}
echo "Original array: ${data[@]}"
for ((i = 0; i < n - 1; i++)); do
min_index=$i
for ((j = i + 1; j < n; j++)); do
if ((data[j] < data[min_index])); then
min_index=$j
fi
done
# Swap the found minimum element with the first element
temp=${data[i]}
data[i]=${data[min_index]}
data[min_index]=$temp
done
echo "Sorted array: ${data[@]}"
Step-by-Step Explanation
NOTE!
This script iteratively selects the smallest element from the unsorted section and swaps it into its correct position in the sorted section.
Here’s how the script works:
- Initialize the Array: Define the sample data as a Bash array.
- Outer Loop: Iterate over each element, treating it as the starting point of the unsorted section.
- Find the Minimum: Use the inner loop to find the smallest element in the unsorted section.
- Swap Elements: Swap the smallest element with the current starting element of the unsorted section.
- Display Results: Print the sorted array after all iterations are complete.
How to Run the Script
Follow these steps to execute the script:
- Save the script to a file, e.g.,
selection_sort.sh
. - Make the script executable by running
chmod +x selection_sort.sh
. - Run the script using
./selection_sort.sh
.
Conclusion
The Selection Sort algorithm is an easy-to-understand sorting method that works well for small datasets. While it is not the most efficient sorting algorithm, it is an excellent way to learn about sorting logic and array manipulation in Bash scripting.
FAQ
-
Is Selection Sort efficient for large datasets?
No, due to its
O(n^2)
time complexity, Selection Sort is not efficient for large datasets. -
Can I use this script for strings?
Yes, you can adapt the comparison logic to use string comparison operators.
-
What happens if the array is already sorted?
The script will still iterate through all elements but will not perform unnecessary swaps.
-
Can this script handle floating-point numbers?
No, Bash only supports integer arithmetic natively. For floating-point numbers, consider using a different language like Python.
Troubleshooting
- Error:
Permission denied
Fix: Ensure the script is executable by runningchmod +x selection_sort.sh
. - Error:
Command not found
Fix: Verify that Bash is installed and the script is being executed with the correct path. - Issue: Incorrect sorting of strings
Fix: Use proper string comparison operators like[[ "${data[j]}" < "${data[min_index]}" ]]
.