In linear search algorithm, we compare the target element with each element of the array. If the element is found, its position is displayed.
The worst-case time complexity of linear search is O(n).
Input: arr[] = { 12, 35, 69, 74, 165, 54} Sea=165 Output: 165 is present at location 5.
Linear search (search algorithm) to find whether a given number exists in an array and if so where does it appear. It is also called sequential search. It's simple and works like this: we keep comparing each element with the element we are searching for until it is found or the list ends.
#include <iostream> using namespace std; int main() { int sea, c, n=6; int arr[] = { 12, 35, 69, 74, 165, 54}; sea=165; for (c = 0; c < n; c++) { if (arr[c] == sea) { printf("%d is present at location %d.\n", search, c+1); break; } } if (c == n) printf("%d isn't present in the array.\n", search); return 0; }
The above is the detailed content of C/C++ program for linear search?. For more information, please follow other related articles on the PHP Chinese website!