[opensuse] bash: insert integer into array in sort order?



Bash gurus,

I have a build script for trinity that accepts package names from the command
line to determine which packages to build. The packages must be built in order.
The array 'bldlist' holds the list of packages in order. Regardless of the order
the package names are entered I need to update the array and insert new integer
values into the array while preserving the sorted order. Basically, the question
is just "how to insert integer values into the array in sorted order?"

I have hacked out an approach that uses case, ifs and fors that works well,
but looking at it -- there has to be a cleaner way. What say the masters? Is
there an easier/simpler way to accomplish this? Here is my cut at the code
(validation, etc. omitted):

#!/bin/bash

[[ -z $1 ]] && { echo "input 1-30 please"; exit 1; }

bldlist=( 5 7 8 12 14 16 19 )
_newval="$1"

_elements=${#bldlist[@]}
_lastidx=$((_elements-1))
inserted=false

## show original array
echo " Original Array"
for((i=0;i<$_elements;i++));do
echo "bldlist[$i] ${bldlist[$i]}"
done
echo ""

case "$_elements" in

## if bldlist is empty, set it to value
0 ) bldlist=( ${_newval} );;

## if bldlist has one element, compare
## and add new value at beginning or end
1 )
if [[ ${_newval} -lt ${bldlist[0]} ]]; then
bldlist=( ${_newval} ${bldlist[@]} )
else
bldlist=( ${bldlist[@]} ${_newval} )
fi
;;

## if bldlist has multiple elements compare
## and insert in sorted location
* )
if [[ ${_newval} -lt ${bldlist[0]} ]]; then
bldlist=( ${_newval} ${bldlist[@]} )

elif [[ ${_newval} -gt ${bldlist[${_lastidx}]} ]]; then
bldlist=( ${bldlist[@]} ${_newval} )

else

for ((n=0;n<${_elements};n++)); do

if [[ ${_newval} -gt ${bldlist[$n]} ]]; then
tmpstr="$tmpstr ${bldlist[$n]}"
continue
elif [[ $inserted == false ]]; then
tmpstr="$tmpstr ${_newval}"
tmpstr="$tmpstr ${bldlist[$n]}"
inserted=true
continue
fi

tmpstr="$tmpstr ${bldlist[$n]}"

done

bldlist=( $tmpstr )

fi
;;
esac

_elements=${#bldlist[@]}

## show new array
echo " New array"
for((i=0;i<$_elements;i++));do
echo "bldlist[$i] ${bldlist[$i]}"
done
echo ""

exit 0


--
David C. Rankin, J.D.,P.E.
--
To unsubscribe, e-mail: opensuse+unsubscribe@xxxxxxxxxxxx
To contact the owner, e-mail: opensuse+owner@xxxxxxxxxxxx