import java.util.StringTokenizer; import java.io.*; // for I/O /* * This program demonstrates the selection sort algorithm. * The program reads in a list of integers (separated by spaces) * and uses the selection sort algorithm to sort these integers * from low to high. The sorted array is then output to the * screen. */ public class SelectionSort { static BufferedReader keyboard = new BufferedReader (new InputStreamReader (System.in)); public static void main (String[] args) throws IOException { StringTokenizer tokenizer; int[] arrayInt; int i, j, smallest, n; int temp; // ask the user for input System.out.print("Enter a list of integers separated by spaces: "); // parse the input and output to the user tokenizer = new StringTokenizer(keyboard.readLine()); n = tokenizer.countTokens(); if (n == 0) { System.out.println("You need to enter at least one number!"); System.exit(-1); } i = 0; arrayInt = new int[n]; while (tokenizer.hasMoreTokens()) { arrayInt[i++] = Integer.parseInt(tokenizer.nextToken()); } System.out.print("The unsorted array is: "); for (i = 0; i < arrayInt.length; i++) System.out.print(arrayInt[i] + " "); System.out.println(); // Selection sort algorithm. for (i = 0; i < arrayInt.length - 1; i++) { smallest = i; for (j = i + 1; j < arrayInt.length; j++) { if (arrayInt[j] < arrayInt[smallest]) smallest = j; } temp = arrayInt[i]; arrayInt[i] = arrayInt[smallest]; arrayInt[smallest] = temp; } System.out.print("The sorted array is: "); for (i = 0; i < arrayInt.length; i++) System.out.print(arrayInt[i] + " "); System.out.println(); } // end of main method } // end of class Tokenize