Advertisement
Guest User

COP 3503C UCF Study Sheet #1

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