Assignment 2

CS 146
due February 19, 2003
60 points

Define a class DuplicateTester that contains methods to determine whether an array of integers contains duplicate elements. This class is to provide the following three public methods: hasDuplicatesUnsorted, hasDuplicates, and hasDuplicatesEfficient. The class is also to be responsible for keeping a count of the number of array element comparisons that it makes, as described below.

The hasDuplicatesUnsorted method is to take as its single argument an array of integers, and return a boolean value which is true if the array has two equal elements in different locations, and false otherwise.

The hasDuplicates method has the same specification, except that it is to use the selectionsort method to sort a copy of the input array, and then check the sorted array for duplicates. You will not be responsible for understanding the selectionsort method until Chapter 12, and you shouldn't need to understand it to complete the assignment.

The hasDuplicatesEfficient method has the same specification, except that it is to use the quickSortWeiss method to sort a copy of the input array, and then check the sorted array for duplicates. You will not be responsible for understanding the quickSortWeiss method in this class (it is covered in CS 146), and you shouldn't need to understand it to complete the assignment. You should be aware that in the average case (for random data) its algorithm is asymptotically more efficient than selection sort, and that using this algorithm will require fewer comparisons of array elements that selection sort will.

Do not print a messsage if and when any of these methods find duplicate elements. Note that you should be able to predict how many element comparisons are made by at least the first of these methods. Make sure that the second and third of these methods do not modify their input array (i.e., that they sort copies of their input arrays and not the arrays themselves).

The DuplicateTester class should also maintain an instance variable counter of the number of comparisons used by its methods. You should provide a public method getCounter() to return the value of the counter, and a public method resetCounter() that sets the value of this counter to 0. It is the responsibility of the user of the class to reset the counter to zero when appropriate.

When you are counting comparisons, be careful that comparisons which are made in the test of an if-statement are counted whether or not the test succeeds. A similar warning applies to for and while loops.

Test your class by executing the test file A2.java, which is provided on the class web site. A skeleton for the DuplicateTester class, with the sorting algorthms that you need provided as private methods, is also given on the class web site. Note that the class A2 invokes the resetCounter() method, and the sorting methods assume the existence of a counter variable. Also note that the sorting methods modify their input arrays.