#!/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. def selection_sort(entries) entries.length.times do |i| # find minimum value in the range i..(entries.length-1) min_idx = i (i+1..entries.length-1).each do |j| min_idx = j if (entries[j] < entries[min_idx]) end # if needed, swap the i-th entry with the min_idx entry next if i == min_idx entries[i],entries[min_idx]=entries[min_idx],entries[i]; end 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 them selection_sort(entries) # display the results entries.each { |entry| puts entry }