import java.util.*;
/**
 * Selection sort routine for arrays
 * @author Suzanne Balik, 6 Nov 2001
 */
public class SelectionSort {

  public static void sort(int[] array) {
  
    for (int i = 0; i < array.length - 1; i++) {
        
      int min = array[i];
      
      int minPos = i;
      
      for (int j = i + 1; j < array.length; j++)
      
        if (array[j] < min) {
	  
	  min = array[j];
	  
	  minPos = j;
	  
	}
	
      if (minPos != i) {
        
	 int tmp = array[i];
	 
	 array[i] = min;
	 
	 array[minPos] = tmp;
      }
	 
    }
  }
  
  public static String toString(int[] array) {
  
    String s = "[";
    for (int i = 0; i < array.length; i++)
      s += " " + array[i];
    s += " ]";
    return s;
  }
  
  public static void main(String[] args) {
  
    int[] array = {2, 8, 1, 3, 4, 5, 7, 6};
    
    System.out.println("Unsorted array: " + 
                        SelectionSort.toString(array));
    SelectionSort.sort(array);
    System.out.println("Sorted array:   " + 
                        SelectionSort.toString(array));
       if (args.length == 1) { 
         array = new int[Integer.parseInt(args[0])];
         Random generator = new Random();
         final int MAX = 200;
         for (int i = 0; i < array.length; i++)
           array[i] = generator.nextInt(MAX);
         long startTime = System.currentTimeMillis();
         SelectionSort.sort(array);
	 long stopTime = System.currentTimeMillis();
         System.out.println("Time to sort " + args[0] + 
                         " random integers in range 1 - 200: " + 
			 (stopTime - startTime) + "ms");
       }
    
  }
}