-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlinearSearch.java
52 lines (41 loc) · 1.33 KB
/
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
40
41
42
43
44
45
46
47
48
49
50
51
52
/*
# write a linear search code for an integer array inputed by the user
steps:
-> take array size input and initialize array
-> take array elements input
-> take input of the element (key) that needs to be searched
-> call a custom function with array and key to search for key
-> it should return the index of 1st occurence of the key, if found
*/
import java.util.Scanner;
public class Main
{
public static void main (String [] args)
{
Scanner sc = new Scanner (System.in);
System.out.print ("Enter array size: ");
int size = sc.nextInt();
int[] array = new int [size];
System.out.print ("Enter integer array elements: ");
for (int i = 0; i < size; i++)
{
array [i] = sc.nextInt();
}
System.out.print ("Enter an integer to search: ");
int key = sc.nextInt();
int index = linearSearch (array, key);
if (index != -1)
System.out.print (key + " found at index: " + index);
else
System.out.print (key + " not found");
}
public static int linearSearch (int array[], int key)
{
for (int i = 0; i <= (array.length-1); i++)
{
if (array [i] == key)
return i;
}
return -1;
}
}