Let's get started with the most basic of searching algorithms, the linear search. It basically involves searching a particular element in a linear array of elements by looking at each of its indices.
Let us suppose an array of integers A contain elements 1,3,4,6,2 and the element to be searched be 4. This is done by looking at each index of A ie. A[0], A[1],..,A[n] and checking if the value contained is equal to the search element 6. Here, n is the number of elements in the array.
Let s be the search element
For each element in the array
{
if array element = search element
Print "element found at" 'array index'
}
//header files
main()
{
int i,s,n,A[10],count=0;
cout<<"Enter number of elements of array:";
cin>>n;
cout<<"Enter elements:";
for(i=0;i<n;i++) //Getting the array
cin>>A[i];
cout<<"Enter element to be searched:";
cin>>s; //Search element
for(i=0;i<n;i++)
{
if(A[i]==s) //Searching
{
cout<< "Element found at index"<<i;
count++;
}
}
if(count==0)
cout<<"Element not found";
}
Let us suppose an array of integers A contain elements 1,3,4,6,2 and the element to be searched be 4. This is done by looking at each index of A ie. A[0], A[1],..,A[n] and checking if the value contained is equal to the search element 6. Here, n is the number of elements in the array.
Pseudocode:
Let s be the search elementFor each element in the array
{
if array element = search element
Print "element found at" 'array index'
}
Sample code in C++:
//header filesmain()
{
int i,s,n,A[10],count=0;
cout<<"Enter number of elements of array:";
cin>>n;
cout<<"Enter elements:";
for(i=0;i<n;i++) //Getting the array
cin>>A[i];
cout<<"Enter element to be searched:";
cin>>s; //Search element
for(i=0;i<n;i++)
{
if(A[i]==s) //Searching
{
cout<< "Element found at index"<<i;
count++;
}
}
if(count==0)
cout<<"Element not found";
}
No comments:
Post a Comment