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.
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++:
#include<iostream> using namespace std; int main() { cout<<"Enter The Size Of Array: "; int size; 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; }
OUTPUT:
Enter The Size Of Array: 5 Enter 0 Element: 8 Enter 1 Element: 2 Enter 2 Element: 1 Enter 3 Element: 3 Enter 4 Element: 9 array[ 0 ] = 8 array[ 1 ] = 2 array[ 2 ] = 1 array[ 3 ] = 3 array[ 4 ] = 9 Enter Key To Search in Array2 Key Found At Index Number : 1 KEY FOUND at index : 1 ...Program finished with exit code 0 Press ENTER to exit console.
Comment in case of any suggestions or issues.