Certainly! Below is a Bash script that implements the Quick Sort algorithm. This script defines a quicksort function that recursively sorts an array of numbers.
Quick Sort Implementation in Bash
bash
#!/bin/bash
# Quick Sort Function
quicksort() {
local array=("$@") # Get all arguments as an array
local length=${#array[@]} # Get the length of the array
# Base case: arrays with 0 or 1 element are already sorted
if (( length <= 1 )); then
echo "${array[@]}"
return
fi
local pivot="${array[0]}" # Choose the first element as the pivot
local less=()
local greater=()
# Partition the array into less and greater arrays
for (( i=1; i<length; i++ )); do
if (( array[i] < pivot )); then
less+=("${array[i]}")
else
greater+=("${array[i]}")
fi
done
# Recursively sort the less and greater arrays
local sorted_less
sorted_less=$(quicksort "${less[@]}")
local sorted_greater
sorted_greater=$(quicksort "${greater[@]}")
# Combine the sorted arrays and pivot
echo $sorted_less $pivot $sorted_greater
}
# Example usage:
# Define an unsorted array
unsorted=(34 7 23 32 5 62)
echo "Unsorted array: ${unsorted[@]}"
# Call quicksort and capture the sorted output
sorted=$(quicksort "${unsorted[@]}")
echo "Sorted array: $sorted"
How It Works
Function Definition:
The quicksort function takes a list of numbers as arguments.
It checks if the array has 0 or 1 element, in which case it's already sorted.
Choosing a Pivot:
The first element of the array is chosen as the pivot.
Partitioning:
The array is partitioned into two sub-arrays:
less: Elements less than the pivot.
greater: Elements greater than or equal to the pivot.
Recursive Sorting:
The quicksort function is called recursively on both less and greater sub-arrays.
Combining Results:
The sorted less array, the pivot, and the sorted greater array are combined and returned.
Example Usage:
An example array unsorted is defined.
The quicksort function is called with this array, and the sorted result is displayed.
Running the Script
Save the Script:
Save the above code to a file, for example, quicksort.sh.
Performance: Bash is not optimized for recursive operations and handling large datasets. This implementation is suitable for educational purposes or sorting small arrays.
Data Types: This script assumes that all elements are integers. For floating-point numbers or more complex data types, additional handling would be required.
Error Handling: The script does not include extensive error handling. Ensure that all inputs are valid integers to avoid unexpected behavior.
Feel free to modify the unsorted array with your own set of numbers to test the Quick Sort implementation!