package findmax;


// turn this into a sorting routine.
// and make the output prettier.


public class FindMax
{
  public static void main(String[] args)
  {
     int [] testArray = {2, 4, 3, 1, 9, 5, 4, 2 } ;
     int i = findMax( testArray ) ;
     System.out.println( i );
     swap( testArray, i, testArray.length-1  ) ;

     printArray( testArray ) ;
  }


  // findMax more general, here it only takes an array,
  // and assumes that you find max in the entire array.
  // a more general, also give it a "size<=a.length".

  static
  int  findMax(int [] a)
  {
     int done, lsf ;

     // L.I. a[lst] := max{ a[0],...,a[done] }
     done = lsf = 0 ;
     // ASSERT: L.I.

     while ( done < (a.length-1) )
     {
        done++ ;
        // L.I. might be broken ...
        if ( a[lsf]<a[done] ) lsf = done ;
        // ASSERT: L.I.
     }
     // GOAL = L.I. and TERMINATION

     return lsf ;
  }

  static
  void swap( int [] a, int i, int j )
  {
     int t ;
     t = a[i] ;
     a[i] = a[j] ;
     a[j] = t ;
  }

  static
  void printArray( int [] a )
  {
     System.out.print("{ ");
     for ( int i=0; i<a.length; i++ )
       System.out.print( a[i]+", " ) ;
     System.out.println("}" );
  }
}