-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinearSearch.cpp
More file actions
62 lines (57 loc) · 1.56 KB
/
linearSearch.cpp
File metadata and controls
62 lines (57 loc) · 1.56 KB
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
53
54
55
56
57
58
59
60
61
62
/*
You have been given a random integer
array/list(ARR) of size N, and an integer X. You
need to search for the integer X in the given
array/list using 'Linear Search'.
You have been required to return the index at
which X is present in the array/list. If X has
multiple occurrences in the array/list, then you
need to return the index at which the first
occurrence of X would be encountered. In case
X is not present in the array/list, then return -1.
'Linear search' is a method for finding an
element within an array/list. It sequentially
checks each element of the array/list until a
match is found or the whole array/list has
been searched.
Input format :
The first line contains an Integer 't' which
denotes the number of test cases or
queries to be run. Then the test cases follow.
First line of each test case or query
contains an integer 'N' representing the
size of the array/list.
Second line contains 'N' single space
separated integers representing the
elements in the array/list.
Third line contains the value of X(integer
to be searched in the given array/list)
*/
#include <iostream>
using namespace std;
int linearSearch(int *arr, int n, int x)
{
for (int i = 0; i <= n-1; i++)
if (arr[i] == x)
return i;
return -1;
}
int main()
{
int t;
cin >> t;
while (t--)
{
int n;
cin >> n;
int *arr = new int[n];
for (int i = 0; i < n; ++i)
{
cin >> arr[i];
}
int val;
cin >> val;
cout << linearSearch(arr, n, val) << endl;
}
return 0;
}