//2012-05-10 johnpfeiffer
// List<String> wordList = Arrays.asList(words);
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
public class SortedPairs
{
ArrayList <IndexValuePair> sortedPairs;
int indexOfMaxValue;
Main( int[] source )
{
this.indexOfMaxValue = getIndexOfMaxValue( source );
sortedPairs = saveValueIndexPairs( source );
System.out.print( "unsorted: " );
consoleLog( sortedPairs );
Collections.sort( sortedPairs , IndexValuePair.COMPARE_BY_VALUE );
System.out.print( " sorted: " );
consoleLog( sortedPairs );
System.out.println( "index " + indexOfMaxValue + " contains the max value of " + source[indexOfMaxValue] );
}
public static void main(String[] args)
{
int example [] = { 4, 3, 1, 4, -1, 2, 1, 5, 7 };
Main m = new Main( example );
}
private ArrayList <IndexValuePair> saveValueIndexPairs( int[] source )
{
ArrayList <IndexValuePair> saved = new ArrayList <IndexValuePair>();
for( int i=0; i<source.length; i++ )
{ IndexValuePair temp = new IndexValuePair( i , source[i] );
saved.add( temp );
}
return saved;
}
private int getIndexOfMaxValue( int[] numbers ) throws IllegalArgumentException
{
if( numbers == null )
{ throw new IllegalArgumentException( "array is null" );
}else
{
int max = numbers[0];
for( int i = 0; i< numbers.length; i++ )
{
if( numbers[i] > numbers[max] ){ max = i; }
}
return max;
}
}
private void consoleLog( int [] numbers ) throws IllegalArgumentException
{
if( numbers == null )
{ throw new IllegalArgumentException( "array is null" );
}else
{
for( int i=0; i < numbers.length; i++)
{ System.out.print( numbers[i] + " , " );
}
}
System.out.println();
}
private void consoleLog( ArrayList <IndexValuePair> numbers ) throws IllegalArgumentException
{
if( numbers == null )
{ throw new IllegalArgumentException( "arrayList is null" );
}else
{
Iterator <IndexValuePair> it = numbers.iterator();
while( it.hasNext() )
{
IndexValuePair temp = it.next();
if( temp != null )
{ System.out.print( temp.getIndex() + "[" + temp.getValue() + "]" + " , " );
}else
{ System.err.println( "Error in arrayList, invalid element" );
}
}
System.out.println();
}
}
public static class IndexValuePair
{
private Integer index;
private Integer value;
IndexValuePair( int i , int v )
{ index = i;
value = v;
}
Integer getIndex()
{ return index;
}
Integer getValue()
{ return value;
}
protected static Comparator<IndexValuePair> COMPARE_BY_VALUE = new Comparator<IndexValuePair>()
{
public int compare( IndexValuePair first , IndexValuePair other )
{ return first.value.compareTo( other.value);
}
};
}
} //end class