|
| 1 | +package com.thealgorithms.searches; |
| 2 | + |
| 3 | +import java.util.Scanner; |
| 4 | + |
| 5 | +public class LinearSearchThread { |
| 6 | + public static void main(String[] args) { |
| 7 | + int[] list = new int[200]; |
| 8 | + for (int j = 0; j < list.length; j++) { |
| 9 | + list[j] = (int) (Math.random() * 100); |
| 10 | + } |
| 11 | + for (int y : list) { |
| 12 | + System.out.print(y + " "); |
| 13 | + } |
| 14 | + System.out.println(); |
| 15 | + System.out.print("Enter number to search for: "); |
| 16 | + Scanner in = new Scanner(System.in); |
| 17 | + int x = in.nextInt(); |
| 18 | + Searcher t = new Searcher(list, 0, 50, x); |
| 19 | + Searcher t1 = new Searcher(list, 50, 100, x); |
| 20 | + Searcher t2 = new Searcher(list, 100, 150, x); |
| 21 | + Searcher t3 = new Searcher(list, 150, 200, x); |
| 22 | + t.start(); |
| 23 | + t1.start(); |
| 24 | + t2.start(); |
| 25 | + t3.start(); |
| 26 | + try { |
| 27 | + t.join(); |
| 28 | + t1.join(); |
| 29 | + t2.join(); |
| 30 | + t3.join(); |
| 31 | + } catch (InterruptedException e) { |
| 32 | + } |
| 33 | + boolean found = t.getResult() || t1.getResult() || t2.getResult() || t3.getResult(); |
| 34 | + System.out.println("Found = " + found); |
| 35 | + } |
| 36 | +} |
| 37 | + |
| 38 | +class Searcher extends Thread { |
| 39 | + private final int[] arr; |
| 40 | + private final int left, right; |
| 41 | + private final int x; |
| 42 | + private boolean found; |
| 43 | + |
| 44 | + Searcher(int[] arr, int left, int right, int x) { |
| 45 | + this.arr = arr; |
| 46 | + this.left = left; |
| 47 | + this.right = right; |
| 48 | + this.x = x; |
| 49 | + } |
| 50 | + |
| 51 | + @Override |
| 52 | + public void run() { |
| 53 | + int k = left; |
| 54 | + found = false; |
| 55 | + while (k < right && !found) { |
| 56 | + if (arr[k++] == x) { |
| 57 | + found = true; |
| 58 | + } |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + boolean getResult() { |
| 63 | + return found; |
| 64 | + } |
| 65 | +} |
0 commit comments