john pfeiffer
  • Home
  • Categories
  • Tags
  • Archives

array quicksort override lessthan

static int[] game( int nPlayers )
{
    int[] result = new int[ nPlayers ];
    for( int i=0; i < nPlayers; i++ )
    {
            result[ i ] = i;
    }
    quicksort( result , 0 , result.length -1 );
    return result;
}

public static void quicksort( int array[], int left, int right )
{
    int mid;
    int temp;
    int i = left;
    int j = right;
    mid = array[ (left + right) / 2 ];

    if( !( lessThan( left , right ) )    )  //base case , equivalent to left >= right
    {       return;
    }

    while( lessThan( i , j ) )
    {
        while( lessThan( array[i] , mid ) )
        {       i++;
        }
        while( lessThan( mid , array[j] ) )
        {       j--;
        }
        if( lessThan( i , j ) )
        {
            temp = array[i];
          array[i] = array[j];
          array[j] = temp;
          i++;
          j--;
        }
    }

    if( lessThan( left , j ) )
    {       quicksort( array , left , j );
    }
    if( lessThan( right , j ) )
    {       quicksort( array , i , right );
    }
}

public static boolean lessThan( int a , int b )
{
    boolean result = false;
    int answer = gameResult( a , b );
    if( a == b )
    {       result = false;
    }else if( answer == a )
    {       result = true;
    }else if( answer == b )
    {       result = false;
    }else
    {   System.out.println( "WTF" );
    }
    return result;
}

    //winner has lower indice = left hand
    public static int gameResult( int a , int b )
    {
        if( a < b )
        {       return a;
        }else
        {       return b;
        }
    }

  • « javascript continued
  • file ReadMore »

Published

May 13, 2012

Category

java

~167 words

Tags

  • array 16
  • java 252
  • override compare 1
  • quicksort 1