// CSE 143, Winter 2011, 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.*; public class SpeedTest { 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 <= 10000; n = n * 2) { timingTest(n); } } // Computes max subsequence sum 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(); int sum = maxSum1(a); long endTime = System.currentTimeMillis(); System.out.println(size + "\t" + (endTime - startTime)); } public static int maxSum1(int[] a) { int max = 0; for (int i = 0; i < a.length; i++) { for (int j = i; j < a.length; j++) { // sum = add the elements from a[i] to a[j]. int sum = 0; for (int k = i; k <= j; k++) { sum += a[k]; } if (sum > max) { max = sum; } } } return max; } public static int maxSum2(int[] a) { int max = 0; for (int i = 0; i < a.length; i++) { int sum = 0; for (int j = i; j < a.length; j++) { sum += a[j]; if (sum > max) { max = sum; } } } return max; } public static int maxSum3(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) } sum += a[j]; if (sum > max) { max = sum; } } return max; } }