#!/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. function selection_sort { local entries_ref=$1 local i j min_idx min_val entries_N eval entries_N=\${#$entries_ref[@]} for i in `seq 0 $[entries_N-1]`; do # find minimum value in the range i..(number_of_entries-1) min_idx=$i eval min_val=\${$entries_ref[$min_idx]} for j in `seq $[i+1] $[entries_N-1]`; do eval val_j=\${$entries_ref[$j]} if [ `bc<<<"$val_j < $min_val"` -eq 1 ]; then min_idx=$j min_val=$val_j fi done # if needed, swap the $i-th entry with the $min_idx entry if [ $min_idx -ne $i ]; then eval $entries_ref[$min_idx]=\${$entries_ref[$i]} eval $entries_ref[$i]=$min_val fi done } if [ $# -ne 1 ]; then echo -e "Usage:\n\t$0 (file with numbers to sort)\n"; exit -1 fi # read in the entries file_name=$1 exec 3<$file_name while read -u 3 inline; do entries[${#entries[@]}]=$inline; done 3>&- # sort them selection_sort entries # display the results for entry in ${entries[@]}; do echo $entry; done