//Sorter.java

import java.util.Arrays;

/**
 * A collection of utility sorting methods.
 * 
 * @author Zach Tomaszewski
 * @version Dec 7, 2006
 */
public class Sorter {
  
  /**
   * Moves all nulls within the array to the end (in an O(n) operation), 
   * then sorts the valid objects remaining (using java.util.Arrays's sort). 
   * 
   * @param array  The array to sort.
   */
  public static void nullSafeSort(Comparable[] array) {
    int end = array.length;
    for (int i = array.length - 1; i >= 0; i--) {
      if (array[i] == null) {
        --end;
        array[i] = array[end];
        array[end] = null;
      }
    }
    Arrays.sort(array, 0, end);
  }

  
  /**
   * Runs a few quick tests of sort methods, print results to the screen.
   * 
   * @param args  Not used.
   */
  public static void main(String[] args) {
    System.out.println("Sample sorts: ");

    Integer[] a1 = {4, 6, 2, 1, -4, 3, 0};
    nullSafeSortTest(a1);
    Integer[] a2 = {null, 6, null, -4, 3, null};
    nullSafeSortTest(a2);
    Integer[] a3 = {null};
    nullSafeSortTest(a3);
    Integer[] a4 = {};
    nullSafeSortTest(a4);

  }

  /**
   * Helper method for testing in main.
   */
  protected static void nullSafeSortTest(Comparable[] a) {
    System.out.print(Arrays.toString(a) + " => ");
    Sorter.nullSafeSort(a);
    System.out.println(Arrays.toString(a));
  }

  
}//end Sorter
