#!/bin/bash

# quicksorts positional arguments
# return is in array qsort_ret
qsort() {
   local pivot i smaller=() larger=()
   qsort_ret=()
   (($#==0)) && return 0
   pivot=$1
   shift
   for i; do
      if [[ $i < $pivot ]]; then
         smaller+=( "$i" )
      else
         larger+=( "$i" )
      fi
   done
   qsort "${smaller[@]}"
   smaller=( "${qsort_ret[@]}" )
   qsort "${larger[@]}"
   larger=( "${qsort_ret[@]}" )
   qsort_ret=( "${smaller[@]}" "$pivot" "${larger[@]}" )
}

array=(a c b "f f" 3 5)


qsort "${array[@]}"

echo ""
echo ""

echo "   The original array was:"
echo "   ======================="
printf "      %s\n" "${array[@]}"

echo ""

echo "   Print sorted array 'qsort_ret' using 'printf'.."
echo "   ==============================================="
printf "      %s\n" "${qsort_ret[@]}"

echo ""

echo "   Print sorted array 'qsort_ret'using 'for'-loop.."
echo "   ================================================"
# the quotes between '${qsort_ret[@]}' are very important
#
for _val in "${qsort_ret[@]}" ; do
   echo "      $_val"
done

echo ""

echo "   Output of command \033[1mdeclare -p qsort_ret\033[m.."
echo "   ====================================================="
echo ""

declare -p qsort_ret

echo -e "\n"
exit 0
