-
Notifications
You must be signed in to change notification settings - Fork 0
/
Linear__Search.java
46 lines (45 loc) · 1.59 KB
/
Linear__Search.java
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
import java.io.FileInputStream;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;
public class Linear__Search {
public static void main(String[] args) throws Exception {
long start2 = System.currentTimeMillis();
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number to search: ");
int input = scanner.nextInt();
FileInputStream fis = null;
fis = new FileInputStream("I:\\test5.txt");
byte[] bytes = fis.readAllBytes();
String numberString = new String(bytes, StandardCharsets.UTF_8);
String[] numberSplit = numberString.split("\\r?\\n ");
boolean flag = false;
int count = 0;
int index = 0;
for(int i=0;i<numberSplit.length;i++)
{
if(input==Integer.parseInt(numberSplit[i]))
{
flag = true;
count++;
index = i;
}
else if(input<Integer.parseInt(numberSplit[i]))
{
break;
}
}
if(flag)
{
System.out.println("Number exists "+count+" times");
System.out.println("Index of first occurrence: "+(index-count+1));
System.out.println("Index of last occurrence: "+index);
}
else
{
System.out.println("Number doesn't exist in file");
}
fis.close();
long end2 = System.currentTimeMillis();
System.out.println("Time taken to execute Linear Search: "+(end2-start2));
}
}