#!/usr/bin/env perl # 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. sub selection_sort($) { my $entries_ref = shift; my ($i, $j, $min_idx, $N_entries_ref, $tmp_swap); for ($i = 0; $i <= $#{$entries_ref}; $i++) { # find minimum value in the range i..(Number_of_entries-1) for ($j = $i+1, $min_idx = $i; $j <= $#{$entries_ref}; $j++) { $min_idx = $j if ($$entries_ref[$j] < $$entries_ref[$min_idx]); } # if needed, swap the $i-th entry with the $min_idx entry next if ($min_idx == $i); ($$entries_ref[$i],$$entries_ref[$min_idx]) = ($$entries_ref[$min_idx],$$entries_ref[$i]); } } if ($#ARGV != 0) { print stderr "Usage:\n\t$0 (file with numbers to sort)\n"; exit -1; } # read in entries $file_name = $ARGV[0]; open fh, $file_name or die "Can't open \"$file_name\"\n"; @entries = ; close fh; # sort them selection_sort(\@entries); # display the results for ($i = 0; $i <= $#entries; $i++) { print "$entries[$i]"; }