Here we will write a program to implement Linear Search C++ programming language, so first lets start with what is linear search and then we will write a program in C++ to implement Linear Search.
“Write a program to implement linear search algorithm in c++”
What is Linear Search:
Linear search or sequential search is a method for finding a target value within a list. It sequentially checks each element of the list for the target value until a match is found or until all the elements have been searched.
Given a list L of n elements with values or records L0 …. Ln−1, and target value T, the following subroutine uses linear search to find the index of the target T in L.
- Set i to 0.
- If Li = T, the search terminates successfully; return i.
- Increase i by 1.
- If i < n, go to step 2. Otherwise, the search terminates unsuccessfully.
Time Complexity:
Worst Case: Linear search runs in at worst linear time and makes at most n comparisons, where n is the length of the list.
Average Case: The average time it takes is n+1/2, where n is the number of elements in the list/series/sequence.
Now lets implement Linear search C++ using above steps:
Program to implement Linear Search C++: Write a program to implement linear search in c++
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 |
#include<iostream> using namespace std; int main() { int size; cout<<"Enter The Size Of Array: "; cin>>size; int array[size], key,i; // Taking Input In Array for(int j=0;j<size;j++){ cout<<"Enter "<<j<<" Element: "; cin>>array[j]; } //Your Entered Array Is for(int a=0;a<size;a++){ cout<<"array[ "<<a<<" ] = "; cout<<array[a]<<endl; } cout<<"Enter Key To Search in Array"; cin>>key; for(i=0;i<size;i++){ if(key==array[i]){ cout<<"Key Found At Index Number : "<<i<<endl; break; } } if(i != size){ cout<<"KEY FOUND at index : "<<i; } else{ cout<<"KEY NOT FOUND in Array "; } return 0; } |
Write a c++ program to implement linear search in one dimensional array.