I'm trying to compare the execution times of brute force search vs binary search on a whitelist.
When I run java BinarySearch tinyW.txt < tinyT.txt
, elapsedTime and the "test" string are not output to console but they are output to console for java BruteForceSearch tinyW.txt < tinyT.txt
.
Note : I'm using external library from here to do the I/O operation.
public class BruteForceSearch {
public static int rank (int key, int[] a) {
for(int i = 0; i < a.length; i++)
if(a[i] == key)
return i;
return -1;
}
public static void main(String[] args) {
long startTime = System.currentTimeMillis();
System.out.println("test");
// read the integers from a file
In in = new In(args[0]);
int[] whitelist = in.readAllInts();
// sort the array
Arrays.sort(whitelist);
// read integer key from standard input; print if not in whitelist
while (!StdIn.isEmpty()) {
int key = StdIn.readInt();
if (rank(key, whitelist) == -1)
StdOut.println(key);
}
long stopTime = System.currentTimeMillis();
long elapsedTime = stopTime - startTime;
System.out.println("elapsed time: " + elapsedTime);
}
}
public class BinarySearch {
public static int rank(int key, int[] a) {
int lo = 0;
int hi = a.length - 1;
while (lo <= hi) {
// Key is in a[lo..hi] or not present.
int mid = lo + (hi - lo) / 2;
if (key < a[mid]) hi = mid - 1;
else if (key > a[mid]) lo = mid + 1;
else return mid;
}
return -1;
}
public static void main(String[] args) {
long startTime = System.currentTimeMillis();
System.out.println("test");
// read the integers from a file
In in = new In(args[0]);
int[] whitelist = in.readAllInts();
// sort the array
Arrays.sort(whitelist);
// read integer key from standard input; print if not in whitelist
while (!StdIn.isEmpty()) {
int key = StdIn.readInt();
if (rank(key, whitelist) == -1)
StdOut.println(key);
}
long stopTime = System.currentTimeMillis();
long elapsedTime = stopTime - startTime;
System.out.println("elapsed time: " + elapsedTime);
}
}
84
48
68
10
18
98
12
23
54
57
48
33
16
77
11
29
23
50
10
99
18
23
98
84
11
10
48
77
13
54
98
77
77
68
java BruteForceSearch tinyW.txt < tinyT.txt
test
50
99
13
elapsed time: 33
java BinarySearch tinyW.txt < tinyT.txt
50
99
13
I copied all those files to a single directory, namely the files:
BinarySearch.java, In.java, StdIn.java, StdOut.java, tinyT.txt, tinyW.txt
Then ran the following:
javac BinarySearch.java
then:
D:\temp\BinarySearch>java BinarySearch tinyW.txt < tinyT.txt
test
50
99
13
elapsed time: 249
Notice it printed the output...
Can you try my same steps?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.