You are on page 1of 5

Cedrick V.

de Guzman CPE 200-CPE21S2


Activity 3.1 Searching Algorithms

Source Code:

#include<iostream>
using namespace std;

int L_search(int arr[],int n,int x)


{
int i,index;
for(i=0;i<n;i++)
if(arr[i]==x)
index = i;
return -1;
}

int Bsearch(int arr[],int n,int x)


{
int low=0;
int high=n-1;
int mid;

while(low<=high)
{
mid=(low+high)/2;
if(x==arr[mid])
{
return mid;
}
else if(x>arr[mid])
{
low=mid+1;
}
else if(x<arr[mid])
{
high=mid-1;
}

return -1;
}

int main(){
string confirm;
cout<<"------WELCOME TO THE ELEMENT SEARCHER!------"<<endl;
int arr[50],n,i;
cout<<"Enter the size of the Array: ";
cin>>n;
cout<<"Enter the elements of the Array: ";
for(i=0;i<n;i++)
cin>>arr[i];
int x;
int mode;
cout<<"Searching Algorithm available\n"
<<"\n__"
<<"\n1. LINEAR SEARCH"
<<"\n2. BINARY SEARCH"
<<"\n___"
<<"\n Choose your method: ";
cin>>mode;

cout<<"Enter a number you want to search:";


cin>>x;
if (mode == 1){
cout<<"YOU HAVE CHOSEN THE LINEAR SEARCHING ALGORITHM"<<endl;
cout<<"INITIATING LINEAR ALGORITHM...."<<endl;
cout<<"..................................................."<<endl;
cout<<"Result not found."<<endl;
cout<<"Restarting the operation..."<<endl;
cout<<"..................................................."<<endl;
cout<<"It is a success!"<<endl;
cout<<"Result Found: "<<endl;
int result=L_search(arr,n,x);
if(result==-1)
cout<<"The Number\t"<< x << "\tis found from the list "<<endl;
else
cout<<"The Number\t" << x << "\tis not found from the list "<<endl;
cout<<"THANK YOU FOR USING NUMBER SEARCHER!";
return 0;
}
else if (mode == 2){
cout<<"YOU HAVE CHOSEN THE BINARY SEARCHING ALGORITHM"<<endl;
cout<<"INITIATING BINARY ALGORITHM...."<<endl;
cout<<"..................................................."<<endl;
cout<<"Result not found."<<endl;
cout<<"Restarting the operation..."<<endl;
cout<<"..................................................."<<endl;
cout<<"It is a success!"<<endl;
cout<<"Result Found: "<<endl;
int result=Bsearch(arr,n,x);
if(result>=0)
cout<<"The Number\t"<< x << "\tis found from the list "<<endl;
else
cout<<"The Number\t" << x << "\tis not found from the list "<<endl;
cout<<"THANK YOU FOR USING NUMBER SEARCHER!";
return 0;
}
else{
}
}
Output:

You might also like