Quicksort in bash
I’m not that much of a shell programmer, but when someone argued on reddit that the shell wasn’t a programming language and that you wouldn’t implement a quick sort in bash for instance, I was quite tempted to try the challenge. Here is the result.
#! /bin/bash -
table=("$@")
quicksort()
{
local low=$1
local high=$2
if ((low >= high)) ; then
return
fi
local pivot=$(((table[low]+table[high])/2))
local i=$low
local j=$high
while ((i < j)) ; do
if ((table[i] <= pivot)) ; then
((i += 1))
elif ((table[j] > pivot)) ; then
((j -= 1))
elif ((i < j)) ; then
local tmp=${table[$i]}
table[$i]=${table[$j]}
table[$j]=$tmp
fi
done
quicksort $low $((i-1))
quicksort $i $high
}
quicksort 0 $((${#table[*]} - 1))
printf "%s\n" "${table[*]}"