Converting pseudocode for array minimum into Java code, using recursion -
i blanking on exam review question, can me started? in findminpos, confused 3 parameters, how access nodes in data array? can use loop though it's recursive method?
public class arrayswapmin { public static void swapmin( int[] data, int cur ) { int min = findminpos( data, cur, cur ); ///////////////////////////////////////////////////////////// // swap min position value 1 in cur position //////////////////////////////////////////////////////////////// } /** * check nodes in "data" position "start" end of array. * see if value in part of array less min * value found far (up "cur" position). */ private static int findminpos( int[] data, int cur, int minpossofar ) { ////////////////////////////////////////////////////////////// // compare entry's value (if valid entry) // value in entry "minpossofar". if value less, // entry "minpossofar". // recurse rest of array. /////////////////////////////////////////////////////////////// return minpossofar; } /** * unit tester */ public static void main( string[] args ) { int[] data = { 12, 3, 10, 5, 1, 8 }; int count = 0; system.out.println( "++++++++++++++++ arrayswapmin ++++++++++++++++" ); printarray( "starting array ", data ); ( int = 0; < data.length - 1; i++ ) { swapmin( data, ); printarray( "swap min " + i, data ); } } public static void printarray( string label, int[] data ) { system.out.print( label + ": [ " ); ( int = 0; < data.length - 1; i++ ) system.out.print( data[ ] + ", " ); system.out.println( data[ data.length - 1 ] + " ]" ); } }
in swapmin()
have switch current position 1 minimum.
public static void swapmin( int[] data, int cur ) { int min = findminpos( data, cur, cur ); int minvalue = data[min]; data[min] = data[cur]; data[cur] = minvalue; }
the minimum recursively determined in findminpos()
. whole idea of recurseiv programming use returnvalues of inner method call instead of using loop. need overall break condition (in case length of array) , multiple return statements.
this 1 here trick:
private static int findminpos( int[] data, int cur, int minpossofar ) { if(cur < data.length) { if(data[cur] < data[minpossofar]) // set new minimum position cur { return findminpos(data, cur + 1, cur); } else // keep old minimum { return findminpos(data, cur + 1, minpossofar); } } return minpossofar; }
and since multiple return statements in if-else block makes code long , messy can shorten this
private static int findminpos( int[] data, int cur, int minpossofar ) { if(cur < data.length) { return (data[cur] < data[minpossofar]) ? findminpos(data, cur + 1, cur) : findminpos(data, cur + 1, minpossofar); } return minpossofar; }
Comments
Post a Comment