forked from manavdoda7/CPP-Programs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinear_search.cpp
More file actions
29 lines (21 loc) · 730 Bytes
/
linear_search.cpp
File metadata and controls
29 lines (21 loc) · 730 Bytes
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
//Linear Search in C++
#include <bits/stdc++.h>
using namespace std;
int search(int arr[], int n, int searchKey) {
/*
Approach:
Traversing through the array and comparing each element of array with the element to be searched.
*/
for (int i=0;i<n;++i){
if(arr[i] == searchKey) return i;
}
return -1; // When element is not found in the array
}
int main() {
int arr[] = {25, 42, 0, 14, 90, 2}; // Intialising an array
int elementToSearch = 14;
int sizeOfArray = sizeof(arr) / sizeof(arr[0]);
int foundAtIndex = search(arr, sizeOfArray, elementToSearch);
if(foundAtIndex == -1)cout << "Element not found";
else cout << "Element found at index: " << foundAtIndex;
}