/* 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. */ import java.io.FileReader; import java.io.BufferedReader; import java.util.ArrayList; public class SelectionSort { // selectionSort - sorts, in place, the items in the ArrayList 'entries' static > void selectionSort(ArrayList entries) { int entriesSize = entries.size(); for (int i = 0; i < entriesSize; i++) { // find minimum value in the range i..(entriesSize-1) int minIdx = i; for (int j = i+1; j < entriesSize; j++) if (entries.get(j).compareTo(entries.get(minIdx)) < 0) minIdx = j; // if needed, swap i-th entry with minIdx entry if (i == minIdx) continue; T tmpSwap = entries.get(i); entries.set(i, entries.get(minIdx)); entries.set(minIdx, tmpSwap); } } static public void main(String[] args) throws Exception { if (args.length != 1) { System.err.println( "Usage:\n\tjava SelectionSort (file with numbers to sort)"); System.exit(-1); } ArrayList entries = new ArrayList(); // read in entries BufferedReader reader = new BufferedReader(new FileReader(args[0])); for (String inLine; (inLine = reader.readLine()) != null; ) entries.add(Float.valueOf(inLine)); // sort them selectionSort(entries); // display the results for (Float entry : entries) System.out.println(entry); reader.close(); } }