list1 = [1, -2, 32, 8, 17, 19, 42, 13, 0, 44]
n = 10
1. Item = 8
index |
0 |
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
elements |
1 |
-2 |
32 |
8 |
17 |
19 |
42 |
13 |
0 |
44 |
The step-by-step process of linear search is as follows:
index |
index < n |
list1[index] = key |
index = index + 1 |
0 |
0 < 10 ? Yes |
1 = 8 ? No |
1 |
1 |
1 < 10 ? Yes |
-2 = 8 ? No |
2 |
2 |
2 < 10 ? Yes |
32 = 8 ? No |
3 |
3 |
3 < 10 ? Yes |
8 = 8 ? Yes |
Therefore, for item 8, linear search returns 3 (index).
2. Item = 1
index |
0 |
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
elements |
1 |
-2 |
32 |
8 |
17 |
19 |
42 |
13 |
0 |
44 |
The step-by-step process of linear search is as follows:
index |
index < n |
list1[index] = key |
index = index + 1 |
0 |
0 < 10 ? Yes |
1 = 1 ? Yes |
Therefore, for item 1, linear search returns 0 (index).
3. Item = 99
index |
0 |
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
elements |
1 |
-2 |
32 |
8 |
17 |
19 |
42 |
13 |
0 |
44 |
The step-by-step process of linear search is as follows:
index |
index < n |
list1[index] = key |
index = index + 1 |
0 |
0 < 10 ? Yes |
1 = 99 ? No |
1 |
1 |
1 < 10 ? Yes |
-2 = 99 ? No |
2 |
2 |
2 < 10 ? Yes |
32 = 99 ? No |
3 |
3 |
3 < 10 ? Yes |
8 = 99 ? No |
4 |
4 |
4 < 10 ? Yes |
17 = 99 ? No |
5 |
5 |
5 < 10 ? Yes |
19 = 99 ? No |
6 |
6 |
6 < 10 ? Yes |
42 = 99 ? No |
7 |
7 |
7 < 10 ? Yes |
13 = 99 ? No |
8 |
8 |
8 < 10 ? Yes |
0 = 99 ? No |
9 |
9 |
9 < 10 ? Yes |
44 = ? No |
10 |
10 |
10 < 10 ? No |
Since the item 99 is not found in the list, the linear search algorithm returns -1.
4. Item = 44
index |
0 |
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
elements |
1 |
-2 |
32 |
8 |
17 |
19 |
42 |
13 |
0 |
44 |
The step-by-step process of linear search is as follows:
index |
index < n |
list1[index] = key |
index = index + 1 |
0 |
0 < 10 ? Yes |
1 = 44 ? No |
1 |
1 |
1 < 10 ? Yes |
-2 = 44 ? No |
2 |
2 |
2 < 10 ? Yes |
32 = 44 ? No |
3 |
3 |
3 < 10 ? Yes |
8 = 44 ? No |
4 |
4 |
4 < 10 ? Yes |
17 = 44 ? No |
5 |
5 |
5 < 10 ? Yes |
19 = 44 ? No |
6 |
6 |
6 < 10 ? Yes |
42 = 44 ? No |
7 |
7 |
7 < 10 ? Yes |
13 = 44 ? No |
8 |
8 |
8 < 10 ? Yes |
0 = 44 ? No |
9 |
9 |
9 < 10 ? Yes |
44 = 44 ? yes |
Therefore, for item 44, linear search returns 9 (index).