// CSE 373, Winter 2013, Marty Stepp // This program performs some operations and // measures and reports the total runtime. // It forms a basis for runtime efficiency testing. import java.util.*; /* alg 1 * 3200 1848 * 6400 15296 * * alg 2 * 51200 522 * 102400 2109 * 204800 8928 * */ public class Lecture04 { public static void main(String[] args) { // perform a timing test for arrays of increasing size (doubling every // time) System.out.println("N\tTime (ms)"); for (int n = 100; n <= 100000000; n = n * 2) { timingTest(n); } } // Computes on a randomly generated array of the given size. public static void timingTest(int size) { // create an array of random data with a mixture of positive and // negative values int[] a = new int[size]; Random rand = new Random(); for (int i = 0; i < a.length; i++) { a[i] = rand.nextInt(1001) - 500; } // get start/stop system times to find out how fast the code ran long startTime = System.currentTimeMillis(); // WRITE THE CODE TO TIME HERE int max = maxSum1(a); long endTime = System.currentTimeMillis(); System.out.println(size + "\t" + (endTime - startTime)); } public static int maxSum1(int[] a) { int max = 0; int sum = 0; int i = 0; for (int j = 0; j < a.length; j++) { if (sum < 0) { // if sum becomes negative, max range i = j; // cannot start with any of i - j-1, sum = 0; // (Claim 2) so move i up to j } sum += a[j]; if (sum > max) { max = sum; } } return max; } }