// CSE 373, Winter 2013 // This program compares the runtime of various operations on sets. import java.util.*; // for Random public class Lecture15RuntimeTest { private static final Random RAND = new Random(42); // random number generator public static void main(String[] args) { int LENGTH = 1000; // initial length of array to sort int RUNS = 13; // how many times to grow by 2? for (int i = 0; i < RUNS; i++) { int[] a = createSequentialArray(LENGTH); Set set = new HashSet(); // perform a sort and time how long it takes long startTime1 = System.currentTimeMillis(); for (int n : a) { set.add(n); } long endTime1 = System.currentTimeMillis(); System.out.printf("%10d elements => %6d ms \n", LENGTH, endTime1 - startTime1); LENGTH *= 2; // double size of array for next time } } // Creates an array of the given length, fills it with random // non-negative integers, and returns it. public static int[] createRandomArray(int length) { int[] a = new int[length]; for (int i = 0; i < a.length; i++) { a[i] = RAND.nextInt(1000000000); } return a; } // Creates an array of the given length, fills it with ordered // non-negative integers, and returns it. public static int[] createSequentialArray(int length) { int[] a = new int[length]; for (int i = 0; i < a.length; i++) { a[i] = i; } return a; } // Creates an array of the given length, fills it with reverse-ordered // non-negative integers, and returns it. public static int[] createReverseArray(int length) { int[] a = new int[length]; for (int i = 0; i < a.length; i++) { a[i] = a.length - 1 - i; } return a; } }