Skip to content

Instantly share code, notes, and snippets.

@milon
Created January 19, 2018 01:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save milon/a3a2fbf2a35c868d14dcc8ba7e04d1fe to your computer and use it in GitHub Desktop.
Save milon/a3a2fbf2a35c868d14dcc8ba7e04d1fe to your computer and use it in GitHub Desktop.
Linear Search
//Linear search
#include<iostream>
using namespace std;
int linear_search(int *a,int size, int key){
for(int i=0;i<size;i++)
if(a[i] == key)
return i+1;
return 0;
}
int main(){
int n, key;
cout<<"How many number do you want: ";
cin>>n;
int arr[n];
cout<<"Enter "<<n<<" numbers:"<<endl;
for(int i=0;i<n;i++)
cin>>arr[i];
cout<<"Enter the searching number: ";
cin>>key;
int res = linear_search(arr, n, key);
if(res==0)
cout<<"Key not found."<<endl;
else
cout<<"Key found at position "<<res<<"."<<endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment