Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public void testSearches() {
- try {
- FileInputStream fstream = new FileInputStream("wordlist.txt");
- DataInputStream in = new DataInputStream(fstream);
- BufferedReader br = new BufferedReader(new InputStreamReader(in));
- List<String> lines = new ArrayList<String>();
- String strLine;
- while ((strLine = br.readLine()) != null) {
- lines.add(strLine);
- }
- in.close();
- long[] totalBinaryResults = new long[3];
- long[] totalLinearResults = new long[3];
- String[] wordlist = lines.toArray(new String[lines.size()]);
- int wordIndex = 1;
- for (String word : wordlist) {
- long[] binaryResults = new long[3];
- long[] linearResults = new long[3];
- int bsResult = Search.binarySearch(wordlist, word, binaryResults);
- int lsResult = Search.linearSearch(wordlist, word, linearResults);
- if( bsResult == -1 || lsResult == -1 ) {
- throw new RuntimeException("A word was not found, the test failed.");
- }
- for (int i = 0; i < linearResults.length; i++) {
- totalBinaryResults[i] += binaryResults[i];
- totalLinearResults[i] += linearResults[i];
- }
- if( linearResults[0] < binaryResults[0] ) {
- System.out.println("Linear search was faster with index "+wordIndex+" ("+word+"): "+
- linearResults[0]+" vs "+binaryResults[0]+" ns, or "+
- linearResults[2]+" vs "+binaryResults[2]+" comparisons");
- }
- wordIndex++;
- }
- System.out.println("*** Binary ***");
- System.out.println("Avg. time: "+totalBinaryResults[0]/(long)wordIndex);
- System.out.println("Avg. comp: "+totalBinaryResults[2]/(long)wordIndex);
- System.out.println("*** Linear ***");
- System.out.println("Avg. time: "+totalLinearResults[0]/(long)wordIndex);
- System.out.println("Avg. comp: "+totalLinearResults[2]/(long)wordIndex);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement