import java.util.Arrays; import java.util.Random; public class HasDupEfficiencyTest { private static final int NUMBER_OF_TESTS = 100; private static final int TEST_ARRAY_LENGTH = 50000; private static long startTime = -1; public static int[] createRandomSortedArray(int size) { Random random = new Random(); int[] array = new int[size]; for (int i = 0; i < size; i++) { array[i] = random.nextInt(NUMBER_OF_TESTS * TEST_ARRAY_LENGTH); } Arrays.sort(array); return array; } public static void startTimer() { HasDupEfficiencyTest.startTime = System.nanoTime(); } /** pre: startTimer has been called and HasDupEfficiencyTest.startTime != -1 */ public static long stopTimer() { long start = HasDupEfficiencyTest.startTime; /* Reset the startTime */ HasDupEfficiencyTest.startTime = -1; return System.nanoTime() - start; } /* pre: array.length >= 1 */ public static long average(long[] array) { long average = array[0]; for (int i = 1; i < array.length; i++) { average = (average * i + array[i]) / (i+1); } return average; } public static boolean hasDuplicate1(int[] array) { for (int i = 0; i < array.length; i++) { for (int j = 0; j < array.length; j++) { if (i != j && array[i] == array[j]) { return true; } } } return false; } public static boolean hasDuplicate2(int[] array) { for (int i = 0; i < array.length - 1; i++) { if (array[i] == array[i+1]) { return true; } } return false; } public static void main(String[] args) { long[] times1 = new long[HasDupEfficiencyTest.NUMBER_OF_TESTS]; long[] times2 = new long[HasDupEfficiencyTest.NUMBER_OF_TESTS]; for (int i = 0; i < HasDupEfficiencyTest.NUMBER_OF_TESTS; i++) { int[] testArray = createRandomSortedArray(HasDupEfficiencyTest.TEST_ARRAY_LENGTH); /* Test hasDuplicate1 */ HasDupEfficiencyTest.startTimer(); hasDuplicate1(testArray); times1[i] = HasDupEfficiencyTest.stopTimer(); /* Test hasDuplicate2 */ HasDupEfficiencyTest.startTimer(); hasDuplicate2(testArray); times2[i] = HasDupEfficiencyTest.stopTimer(); } System.out.println("hasDuplicate1 average run time is " + average(times1) + " ns."); System.out.println("hasDuplicate2 average run time is " + average(times2) + " ns."); } }