Created
September 28, 2016 16:20
-
-
Save Lipen/b0c147f082aa496f2060af6082b229cf to your computer and use it in GitHub Desktop.
Bash quicksort
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
quicksort() { | |
local i m | |
quicksort_return=() | |
local left=() right=() | |
(($#==0)) && return 0 | |
m=$1 | |
# echo "Pivot: <$m>" | |
shift | |
for i; do | |
if [[ $i < $m ]]; then | |
left+=( $i ) | |
else | |
right+=( $i ) | |
fi | |
done | |
# echo "Left: [${left[@]}]" | |
# echo "Right: [${right[@]}]" | |
quicksort "${left[@]}" | |
left=( "${quicksort_return[@]}" ) | |
quicksort "${right[@]}" | |
right=( "${quicksort_return[@]}" ) | |
quicksort_return=( "${left[@]}" "$m" "${right[@]}" ) | |
# echo "Returning [${quicksort_return[@]}]" | |
} | |
data=(4 9 2 6 3 8 1 5) | |
echo "Initial data: [${data[@]}]" | |
quicksort "${data[@]}" | |
echo "Sorted: [${quicksort_return[@]}]" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment