#!/bin/sh # Copyright 2005 Daniel Cer (daniel.cer@cs.colorado.edu) # # This work is licensed under the Creative Commons Attribution-NonCommercial- # ShareAlike License. To view a copy of this license, visit # http://creativecommons.org/licenses/by-nc-sa/2.5/ or send a letter to # Creative Commons, 543 Howard Street, 5th Floor, San Francisco, California, # 94105, USA. # bubble_sort - sorts the array referenced by the first argument to this # function. # # e.g. to sort an array '$entries[@]', the following statement would be # used: bubble_sort entries function bubble_sort { local entries_ref=$1 local i j entries_N val_j val_j_inc eval entries_N=\${#$entries_ref[@]} for i in `seq $[entries_N-1] -1 0`; do for j in `seq 0 $[i-1]`; do eval val_j=\${$entries_ref[$j]} eval val_j_inc=\${$entries_ref[$[j+1]]} if [ `bc<<<"$val_j_inc < $val_j"` -eq 1 ]; then eval $entries_ref[$j]=$val_j_inc eval $entries_ref[$[$j+1]]=$val_j fi done done } if [ $# -ne 1 ]; then echo -e "Usage:\n\t$0 (file with numbers to sort)" >&2 exit -1 fi # read in the items exec 3<$1 while read -u 3 entry; do entries[${#entries[@]}]=$entry; done 3>&- # sort them bubble_sort entries # display the sorted results for entry in ${entries[@]}; do echo $entry; done