-
-
Notifications
You must be signed in to change notification settings - Fork 155
Expand file tree
/
Copy pathReadFromFile.java
More file actions
68 lines (56 loc) · 1.89 KB
/
Copy pathReadFromFile.java
File metadata and controls
68 lines (56 loc) · 1.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package util;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReadFromFile {
static boolean linearSearchAlgorithm1(int[] arr, int numberToFind) {
for (int i = 0; i < arr.length; i++) {
if (numberToFind == arr[i])
return true;
}
return false;
}
static boolean binarySearchAlgorithm2(int[] arr, int numberToFind) {
int left = 0, right = arr.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == numberToFind) return true;
if (arr[mid] < numberToFind) left = mid + 1;
else right = mid - 1;
}
return false;
}
public static void main(String[] args) {
int[] ints = new int[10000001]; // 10 million size
long start, finish, timeElapsed;
boolean result;
int index = 0;
// Some code to read from file into the array ints
try {
File myObj = new File("integers.txt");
Scanner myReader = new Scanner(myObj);
while (myReader.hasNextLine()) {
String data = myReader.nextLine();
ints[index++] = Integer.parseInt(data);
}
myReader.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
System.out.println("\n===== USING ALGORITHM 1 =====");
start = System.nanoTime();
result = linearSearchAlgorithm1(ints, 5);
finish = System.nanoTime();
timeElapsed = finish - start;
System.out.print(result ? "Found" : "Not Found");
System.out.println("\nTime Taken: " + timeElapsed + " ns");
System.out.println("\n===== USING ALGORITHM 2 =====");
start = System.nanoTime();
result = binarySearchAlgorithm2(ints, 5);
finish = System.nanoTime();
timeElapsed = finish - start;
System.out.print(result ? "Found" : "Not Found");
System.out.println("\nTime Taken: " + timeElapsed + " ns");
}
}