-
Notifications
You must be signed in to change notification settings - Fork 70
/
Copy pathLinear search algorithm
73 lines (54 loc) · 1.63 KB
/
Linear search algorithm
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
63
64
65
66
67
68
69
70
71
72
73
Linear Search is defined as a sequential search algorithm that starts at one end and goes through each element of a list until the desired element is found,
otherwise the search continues till the end of the data set. It is the easiest searching algorithm
Follow the below idea to solve the problem:
Iterate from 0 to N-1 and compare the value of every index with x if they match return index
Follow the given steps to solve the problem:
Start from the leftmost element of arr[] and one by one compare x with each element of arr[]
If x matches with an element, return the index.
If x doesn’t match with any of the elements, return -1.
Input: arr[] = {10, 20, 80, 30, 60, 50,110, 100, 130, 170}, x = 110;
Output: 6
Explanation: Element x is present at index 6
Input: arr[] = {10, 20, 80, 30, 60, 50,110, 100, 130, 170}, x = 175;
Output: -1
Explanation: Element x is not present in arr[].
#include<bits/stdc++.h>
using namespace std;
// } Driver Code Ends
class Solution{
public:
int search(int arr[], int N, int X)
{
int search(int arr[], int N, int X)
{
for(int i=0;i<N;i++)
{
if(arr[i]==X)
{
return i;
}
}
return -1;
}
}
};
int main()
{
int testcases;
cin>>testcases;
while(testcases--)
{
int sizeOfArray;
cin>>sizeOfArray;
int arr[sizeOfArray];
int x;
for(int i=0;i<sizeOfArray;i++)
{
cin>>arr[i];
}
cin>>x;
Solution ob;
cout<<ob.search(arr,sizeOfArray,x)<<endl; //Linear search
}
return 0;
}