-
Notifications
You must be signed in to change notification settings - Fork 1
/
LinearSearch.java
39 lines (34 loc) · 925 Bytes
/
LinearSearch.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
package dsa;
import java.util.Arrays;
import java.util.Scanner;
public class LinearSearch {
//function for linearsearch
static void linearsearch(int arr[], int item) {
int count = 0;
for(int i=0; i<arr.length; i++) {
if(arr[i] == item) {
System.out.println("The item "+item+" is found at "+i+"th position");
count++;
}
}
if(count == 0) {
System.out.println("Item not found");
}
}
//driver code
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter array size");
int size = sc.nextInt();
System.out.println("Enter array elements");
int arr[] = new int[size];
for(int i=0; i<arr.length; i++) {
arr[i] = sc.nextInt();
}
System.out.println("Array is "+Arrays.toString(arr));
System.out.println("Enter the item to search");
int item = sc.nextInt();
//call the linear method to search
linearsearch(arr, item);
}
}