
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
C++ Program for Linear Search
In linear search algorithm, we compare targeted element with each element of the array. If the element is found then its position is displayed.
The worst case time complexity for linear search is O(n).
Input: arr[] = { 12, 35, 69, 74, 165, 54} Sea=165 Output: 165 is present at location 5.
Explanation
linear search (Searching algorithm) which is used to find whether a given number is present in an array and if it is present then at what location it occurs. It is also known as sequential search. It is straightforward and works as follows: We keep on comparing each element with the element to search until it is found or the list ends.
Example
#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; }
Advertisements