#!/usr/bin/env ruby # 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. # insertion_sort - sort, in place, the list given by 'entries' # As a convenience, the list 'entries' is also returned by this function def insertion_sort(entries) e = entries # shortened alias for list given by 'entries' 1.upto(e.length-1) do |i| j = nil; value = e[i] if (i-1).downto(0) { |j| break if (e[j] <= value); e[j+1] = e[j] } then e[0] = value # place 'value' at the very begining of the sorted list else e[j+1] = value # place 'value' just after the entry at position 'j' end; end; entries end if ARGV.length != 1 $stderr.puts "Usage:\n\t#{$0} (file with numbers to sort)" exit -1 end # read in the entries entries = Array.new; IO.foreach(ARGV[0]) { |line| entries.push Float(line) } # sort the entries & the display the sorted results insertion_sort(entries).each { |line| puts line }