Advertisement
Guest User

COP 3503C UCF Study Sheet #1

a guest
Sep 16th, 2014
239
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //used code from the following source: http://www.cs.ucf.edu/~dmarino/ucf/cop3503/lectures/AlgAnalysis03.doc
  2. public class practice {
  3.     public static void main(String[] args){
  4.         int[] a = {9, -3, 7, -12, 3, -2, 5, -8, 8, 13, -20, 6, -4, 3, -5, 3, -2, 18, 9, -4, 5};
  5.         MCSS(a);//this tests the O(n^2)
  6.         MCSS2(a);//this tests the O(n)
  7.     }
  8.     //this tests the O(n^2)
  9.     public static int MCSS(int [] a) {
  10.          int max = 0, sum = 0, start = 0, end = 0;
  11.          int count=0;
  12.          // Try all possible values of start and end indexes for the sum.
  13.          for (int i = 0; i < a.length; i++) {
  14.               sum = 0;
  15.               for (int j = i; j < a.length; j++) {
  16.                    sum += a[j]; // No need to re-add all values.
  17.                    if (sum > max) {
  18.                        count++;
  19.                        System.out.printf("Changed max at i= %d and j= %d\n"
  20.                             + "\tNew max: %d\n"
  21.                             + "\tChanges so far: %d\n", i, j, sum, count);
  22.                        max = sum;
  23.                        start = i; // Although method doesn't return these
  24.                        end = j;  // they can be computed.
  25.                    }
  26.               }      
  27.          }
  28.          System.out.printf("max: %d\n", max);
  29.          return max;
  30.     }
  31.     //this tests the O(n)
  32.     public static int MCSS2(int [] a) {
  33.  
  34.          int max = 0, sum = 0, start = 0, end = 0, i=0;
  35.          int count = 0;
  36.      
  37.          // Cycle through all possible end indexes.
  38.          for (int j = 0; j < a.length; j++) {
  39.            
  40.               sum += a[j]; // No need to re-add all values.
  41.               if (sum > max) {
  42.                   count++;
  43.                   System.out.printf("Changed max at i=%d and j=%d\n"
  44.                             + "\tNew max: %d\n"
  45.                             + "\tChanges so far: %d\n", i, j, sum, count);
  46.                   max = sum;
  47.                   start = i; // Although method doesn't return these
  48.                   end = j;  // they can be computed.
  49.               }
  50.               else if (sum < 0) {
  51.                    i = j+1; // Only possible MCSSs start with an index >j.
  52.                    sum = 0; // Reset running sum.
  53.               }      
  54.          }
  55.          System.out.printf("max: %d\n", max);
  56.          return max;
  57.     }
  58.  
  59.  
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement