Question : There is an array of integers.You are given an element.Search the element in the array in 0(n) complexity and return its index.

Algorithm : Step 1 : Traverse the array one by one element and compare each element of the array with the number to be searched. Step 2 : Once we get equality ,we are printing the element and its position in the array.

The method linearSearchFirst() is accepting two arguments .First argument is the array and second argument is the element to be searched.The element to be searched is compared with each element in the array and once we find the match, we are exiting from the for loop.

The method linearSearchAll() is accepting two arguments .First argument is the array and second argument is the element to be searched..The element to be searched is compared with each element in the array and whenever we get equalities, we are printing its occurrence.If the element is not present in the array ,we are printing the negative message.

Program :

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

packagecom.ajay.search.pkg;

publicclassLinearSearch

{

publicstaticvoidmain(String[]args)

{

int[]arr={5,9,-6,7,8,-9,10,77,8,56};

linearSearchFirst(arr,10);

linearSearchFirst(arr,11);

linearSearchAll(arr,8);

linearSearchAll(arr,11);

}

privatestaticvoidlinearSearchFirst(int[]arr,intelement)

{

booleanisPresent=false;

System.out.println("Inside method linearSearchFirst ");

for(inti=0;i<arr.length;i++)

{

if(element==arr[i])

{

System.out.println("Element "+element+" is present at position "+(i+1));

isPresent=true;

break;

}

}

if(!isPresent)

{

System.out.println("Element "+element+" is not present ");

}

}

privatestaticvoidlinearSearchAll(int[]arr,intelement)

{

booleanisPresent=false;

System.out.println("Inside method linearSearchAll ");

for(inti=0;i<arr.length;i++)

{

if(element==arr[i])

{

System.out.println("Element "+element+" is present at position "+(i+1));

About the Author

Dear Friends,
I am A.K.M. .This online journal ai1tutorial.com is a humble effort from my side to all students and professionals who want to learn computer science related technologies.I am not a professional blogger and I write posts in this blog only in my leisure time.I may not be 100% perfect in all my posts,but your review comments can surely help me to make it 100% perfect.