/**
 * Sort implements some sorting algorithms.
 *
 * @author     heap
 * @created    April 10, 2002
 */
public class Sort {
  // no constructor

  /**
   * insertionSort: put elements of list into non-descending order
   *
   * @param  list  unsorted array of integers
   */
  public void insertionSort(int[] list) {
    // for each item in the list
    // list[0..i-1] is sorted && list[i..list.length-1] unsorted
    for (int i = 1; i != list.length; i++) {
      // put list[i] in its place in list[0..i-1], moving
      // larger elements up
      int t = list[i];
      int j; // must exist outside the for loop
      // list[j+1..i] contain elements of list[0..i-1] that
      // were > t
      for (j= i; j != 0 && list[j-1] > t; j--) {
	list[j] = list[j - 1];
      }
      // list[j+1..i] contain elements of list[0..i-1] that were
      // > t && list[0..j-1] contain elements of list[0..i-1] <= t
      list[j] = t;
    }
    // list[0..list.length-1] is sorted &&
    // list[list.length..list.length-1] unsorted
  }

  /** selectionSort: put elements of list into non-descending order
   */
  public void selectionSort(int[] list) {
    // list[0..i-1] is sorted in non-decreasing order &&
    // list[0..i-1] <= list[i..list.length-1]
    for (int i= 0; i != list.length; i++) {
      int smallest= i;
      // list[smallest] <= list[i..j-1]
      for (int j= i+1; j != list.length; j++) {
	if (list[j] < list[smallest]) {smallest= j;}
      }
      // list[smallest] <= list[i..list.length-1]
      int tmp= list[smallest];
      list[smallest]= list[i];
      list[i]= tmp;
      // list[i] <= list[i..list.length-1]
    }
    // list[0..list.length-1] is sorted in non-decreasing order &&
    // list[0..list.length-1] <= list[list.length..list.length-1]
  }

  /**
   *  The main program for the Sort class
   *
   * @param  args  The command line arguments
   */
  public static void main(String[] args) {
    Sort s1= new Sort();
    int[] list= {5,3,3,2,7,8,9,-136};
    int[] list2= {9, 8, 7, 6, 5, 4, 3, 2, 1};
    s1.insertionSort(list);
    s1.selectionSort(list2);
  }

}


