- Notifications
You must be signed in to change notification settings - Fork 19.9k
/
Copy pathLinearSearchThread.java
74 lines (69 loc) · 2.21 KB
/
LinearSearchThread.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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
packagecom.thealgorithms.searches;
/**
* LinearSearchThread is a multithreaded implementation of the linear search algorithm.
* It creates multiple threads to search for a specific number in an array.
*
* <p>
* The class generates an array of random integers, prompts the user to enter a number to search for,
* and divides the array into four segments, each handled by a separate thread.
* The threads run concurrently and search for the specified number within their designated segments.
* Finally, it consolidates the results to determine if the number was found.
* </p>
*
* <p>
* Example usage:
* 1. The program will output the generated array.
* 2. The user will be prompted to input a number to search for.
* 3. The program will display whether the number was found in the array.
* </p>
*/
publicfinalclassLinearSearchThread {
privateLinearSearchThread() {
}
}
/**
* The Searcher class extends Thread and is responsible for searching for a specific
* number in a segment of an array.
*/
classSearcherextendsThread {
privatefinalint[] arr; // The array to search in
privatefinalintleft; // Starting index of the segment
privatefinalintright; // Ending index of the segment
privatefinalintx; // The number to search for
privatebooleanfound; // Result flag
/**
* Constructor to initialize the Searcher.
*
* @param arr The array to search in
* @param left The starting index of the segment
* @param right The ending index of the segment
* @param x The number to search for
*/
Searcher(int[] arr, intleft, intright, intx) {
this.arr = arr;
this.left = left;
this.right = right;
this.x = x;
}
/**
* The run method for the thread, performing the linear search in its segment.
*/
@Override
publicvoidrun() {
intk = left;
found = false;
while (k < right && !found) {
if (arr[k++] == x) {
found = true;
}
}
}
/**
* Returns whether the number was found in the segment.
*
* @return true if the number was found, false otherwise
*/
booleangetResult() {
returnfound;
}
}