C/C++ Program for Linear Search
Problem: Given an array arr[] of n elements, write a function to search a given element x in arr[].
C/C++
#include <bits/stdc++.h> using namespace std; // Linearly search x in arr[]. If x is present then return its // location, otherwise return -1 int search(int arr[], int n, int x) { int i; for (i = 0; i < n; i++) if (arr[i] == x) return i; return -1; } // Driver code int main() { int arr[] = { 3, 4, 1, 7, 5 }; int n = sizeof(arr) / sizeof(arr[0]); int x = 4; int index = search(arr, n, x); if (index == -1) cout << "Element is not present in the array"; else cout << "Element found at position " << index; return 0; } |
chevron_right
filter_none
Output:
Element found at position 1
The time complexity of the above algorithm is O(n).
Please refer complete article on Linear Search for more details!
Recommended Posts:
- Java Program for Linear Search
- Linear Search vs Binary Search
- Linear Search
- Linear search using Multi-threading
- C Program for Anagram Substring Search (Or Search for all permutations)
- Lex program to search a word in a file
- C Program for Binary Search (Recursive and Iterative)
- Recursive program to linearly search an element in a given array
- Repeatedly search an element by doubling it after every successful search
- Why is Binary Search preferred over Ternary Search?
- Interpolation search vs Binary search
- Best First Search (Informed Search)
- Median of two sorted arrays of different sizes | Set 1 (Linear)
- Meta Binary Search | One-Sided Binary Search
- Sublist Search (Search a linked list in another list)



