/**
 * Use Comparable interface to allow objects that implement it to be sorted.
 * Note that the same method can sort different object types. We got as far as
 * testing Integer (successfully) and String (unsuccessfully) in class. The
 * working version below has the correct test for the return value of compareTo,
 * checking for any negative integer not just -1.
 * 
 * Lecture 21, Thu Mar 21 2006, CPSC 111
 */
public class Sorter
{
	//public void sort( Comparable[] objects )
	/* We tried both a static version and a nonstatic version of this code in class.
	 * Since there are no nonstatic fields used in the method, it's safe to make it static.
	 */
	
	/**
	 * Sort an array of any objects that implement the Comparable interface.
	 */
	public static void sort( Comparable[] objects ) // static version
	{
		
		//int temp;
		/* Above is old code, change from int to Comparable */
		Comparable temp; 
		int min;
		// select location of next sorted value
		for( int i = 0; i < objects.length - 1; i++ )
		{
			min = i;
			// find the smallest value in the remainder of
			// the array to be sorted
			for( int j = i + 1; j < objects.length; j++ )
			{
				// if( objects[ j ] < objects[ min ] )
				/* Above is the old code, to sort integers */
				
				//if( objects[ j ].compareTo( objects[ min ] ) == -1 )
				/*
				 * Above was our first try in class. Sadly, slide was wrong. In
				 * fact, compareTo can return any value less than 0, not just
				 * -1, to denote the "less than" state.
				 */
				if( objects[ j ].compareTo( objects[ min ] ) < 0 )
				{
					min = j;
				}
			}
			// swap two values in the array
			temp = objects[ i ];
			objects[ i ] = objects[ min ];
			objects[ min ] = temp;
		}
		
		System.out.println( "Printing sorted result" );
		for( int i = 0; i < objects.length; i++ )
		{
			System.out.println( objects[ i ] );
		}
	}
	
	public static void main( String[] args )
	{
		// int[] numbers = {16,3,19,8,12};
		Integer[] numbers = new Integer[ 5 ];
		numbers[ 0 ] = new Integer( 16 );
		numbers[ 1 ] = new Integer( 3 );
		numbers[ 2 ] = new Integer( 19 );
		numbers[ 3 ] = new Integer( 8 );
		numbers[ 4 ] = new Integer( 12 );
		
		// Sorter s = new Sorter();  // nonstatic version
		// s.sort( numbers );
		/* Above code was for the nonstatic experiment. */
		
		// sort (numbers);
		/* Above code was our original static call. But it's cleaner to use the
		 * class name so that this line would work from any program, not just
		 * the internal main driver.
		 */
		Sorter.sort( numbers );
		
		String[] strings = new String[4];
		strings[0] = new String("the");
		strings[1] = new String("ame");
		strings[2] = new String("cat");
		strings[3] = new String("dog");
		
		Sorter.sort(strings);       
	}
	
}
