Question: Write a test program to test the 3 given uniqueness methods for identification of uniqueness of the contents of an array. a. You may need
Write a test program to test the 3 given uniqueness methods for identification of uniqueness of the contents of an array. a. You may need in the test program to define an array of integers as the testing data. Preferably, write code to generate data, save to a text file, and read it back for testing (sample code provided in InputOutput.java program). b. Test the 3 methods/algorithms with carefully prepared data, record the execution times, jot down the times vs data size. c. You are to answer Big-Oh related questions for the methods/algorithms. d. The work will prepare for your big-Oh project.
import java.util.Arrays;
class Uniqueness {
/** Returns true if there are no duplicate elements in the array. */ public static boolean unique1(int[] data) { int n = data.length; for (int j=0; j < n-1; j++) for (int k=j+1; k < n; k++) if (data[j] == data[k]) return false; // found duplicate pair return true; // if we reach this, elements are unique }
/** Returns true if there are no duplicate elements in the array. */ public static boolean unique2(int[] data) { int n = data.length; int[] temp = Arrays.copyOf(data, n); // make copy of data Arrays.sort(temp); // and sort the copy for (int j=0; j < n-1; j++) if (temp[j] == temp[j+1]) // check neighboring entries return false; // found duplicate pair return true; // if we reach this, elements are unique }
}
///////////////////////////
public class Unique3 {
/** Returns true if there are no duplicate values from data[low] through data[high].*/ public static boolean unique3(int[] data, int low, int high) { if (low >= high) return true; // at most one item else if (!unique3(data, low, high-1)) return false; // duplicate in first n-1 else if (!unique3(data, low+1, high)) return false; // duplicate in last n-1 else return (data[low] != data[high]); // do first and last differ? } }
/////////////////////
import java.io.IOException; import java.util.Formatter; import java.util.Scanner; import java.nio.file.Paths;
public class InputOutput { public static void main(String[] args) throws IOException { //output to a text file Formatter output = new Formatter("testData.txt"); output.format("%d %d %d", 123, 2, 3); output.close(); //read from a text file that contains integers Scanner input = new Scanner(Paths.get("testData.txt")); int x; while (input.hasNext()){ x = input.nextInt(); System.out.printf("%d, ", x); } input.close(); System.out.println(" HHHHHHHHHHHHHh"); } }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
