CSC300: Another way to compute max [19/21] Previous pageContentsNext page

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package algs11;
import stdlib.*;
public class PlaygroundMax {
  public static double max (double[] a) {
    for (int i=0; i < a.length; i++) {
      boolean isMax = true;
      for (int j=0; j<a.length; j++)
        if (a[j] > a[i])
          isMax = false;
      if (isMax) return a[i];
    }
    throw new IllegalArgumentException(); 
  }
  public static void testMax (double expected, double[] a) {
    double actual = max (a);
    if (expected != actual) {
      StdOut.format ("max failed: Expecting [%d] Actual [%d] with argument %s\n", expected, actual, java.util.Arrays.toString(a));
    }
  }
  public static void main (String[] args) { 
    testMax(31, new double[] { 11, 21, 31 });
    testMax(31, new double[] { 11, 31, 21 });
    testMax(31, new double[] { 31, 11, 21 });
    testMax(21, new double[] { 21, 11 });
    testMax(21, new double[] { 11, 21 });
    testMax(11, new double[] { 11 });
    try {
      max (new double[] { });
      StdOut.println ("max failed: Expecting [IllegalArgumentException] with argument [ ]");
    } catch (IllegalArgumentException e) { }
    StdOut.println ("Finished tests");
  }
}

Are these solutions of equal quality?

Previous pageContentsNext page