Question: Java, I need HELP please. public class CSC300Homework4 { /** * As a model for Problem 1, here are two functions to find the minimum
Java, I need HELP please.
public class CSC300Homework4 {
/** * As a model for Problem 1, here are two functions to find the minimum value of an array of ints * an iterative version and a recursive version * * precondition: list is not empty /** iterative version */ public static double minValueIterative (int[] list) { int result = list[0]; int i = 1; while (i < list.length) { if (list[i] < result) result = list[i]; i = i + 1; } return result; }
/** recursive version * Find minimum of a list of size N starting at location 0 * Smaller problem is : Find minimum of list of size N-1, starting at 0 * * precondition: list is not empty */ public static int minValueRecursive (int[] list) { return minValueHelper (list, list.length); } private static int minValueHelper (int[] list, int n) { if (n == 1) // the list of size 1 is the single element list[0] return list[0]; // the minimum of this list is just that element.
// else: find minimum of smaller list
int minOfSmallerList = minValueHelper( list, n-1); // recursive call, 'smaller' list
// now compare min of smaller list to 'last' element of this list // the list is of size n, the 'last' element is at position n-1 // because indexes start at 0. int theMin;
if ( list[n-1] < minOfSmallerList) theMin = list[n-1]; else theMin = minOfSmallerList;
return theMin; }
/** * PROBLEM 1: Translate the following summing function from iterative to * recursive. * * You should write a helper method. You may not use any "fields" to solve * this problem (a field is a variable that is declared "outside" of the * function declaration --- either before or after). * * Precondition: a list of ints, - maybe empty! * Postcondition: the sum of the positive values is returned */ public static int sumOfPositives (int[] a) { int result = 0; int i = 0; while (i < a.length) { if ( a[i] > 0) result = result + a[i]; i = i + 1; } return result; }
public static int sumOfPositivesRecursive (int[] a) { return -1; // TODO 1 replace this by a call to your helper function, then write the helper function below } // this would be a good place to put the helper function for #1 /** * Here is an in-place iterative function to reverse an array. * * in-place means: we don't create an extra array (to simplify coding) * */ public static void reverseIterative (int[] a) { int hi = a.length - 1; int lo = 0; while (lo < hi) { int loVal = a[lo]; int hiVal = a[hi]; a[hi] = loVal; a[lo] = hiVal; lo = lo + 1; hi = hi - 1; } }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
