Você está na página 1de 4

ONE DIMENSIONAL ARRAY 1

DATE

Qn. Write a menu driven progtram to perform the following operations using
functions:
1.linearsearch(int [],int)- to search for a given element and return 1 if element
found and otherwise return 0.(print appropriate message)
2.binarysearch(int [],int)-to search a sorted array for a specific element and dispaly
the first occurence of the element.
3.swapp(int [],int)-to swap the old elements and dispaly the old and new array.

#include<iostream.h>
#include<conio.h>
#include<math.h>
int go;
int linearsearch(int arr[],int m){
int se,flag,pos;
cout<<"\n enter the element to be searched:";
cin>>se;
for(int z=0;z<m;z++){
if(arr[z]==se){
pos=z;
go=++pos;
flag=0;
break;
}
}
if (flag==0){
return 1; }

else
{
return 0; }
}
void binarysearch(int az[],int s){
int lb=0;
int ub=s-1;
int flag;
int d;
cout<<"\n enter the value to be searched";
cin>>d;
while(lb<=ub){
int mv=(lb+ub)/2;
if(az[mv]==d)
{
cout<<"\n element found at position:"<<mv+1;
flag=0;
break;

}
else if(d<az[mv])
ub=mv-1;
else if(d>az[mv])
lb=mv+1;

flag=1;
}
if(flag==1)
cout<<"\n element not found";

void swapp(int swap[],int si){


int z;
for(int a=0;a<si-1;a+=2)
{ z=swap[a];
swap[a]=swap[a+1];
swap[a+1]=z;
}
cout<<"\n array after swapping=";
for(int i=0;i<si;i++)
cout<<swap[i]<<" ";
}
void main(){
clrscr();
int op;
char ans;
do{
cout<<"\n menu";
cout<<"\n 1.linear search";
cout<<"\n 2.binary search ";
cout<<"\n 3.swaping numbers ";
cout<<"\n enter your choice";
cin>>op;

if(op==1){
int a[100];
int l;

cout<<"\n enter the limit:";


cin>>l;
for(int i=0;i<l;i++){
cout<<"\n enter the value:";
cin>>a[i];
}
int f=linearsearch(a,l);
if(f==1)
cout<<"\n element found at position "<<" "<<go;
else
cout<<"\n element not found";
}

else if(op==2){
int a[100];
int l;

cout<<"\n enter the limit:";


cin>>l;
for(int i=0;i<l;i++){
cout<<"\n enter the value:";
cin>>a[i];
}
binarysearch(a,l);

}
else if(op==3){
int a[100];
int l;

cout<<"\n enter the limit:";


cin>>l;
for(int i=0;i<l;i++){
cout<<"\n enter the value:";
cin>>a[i];
}
swapp(a,l);
}

else
cout<<"\ invalid input";
cout<<"\n do you want to continue ?";
cin>>ans;}while(ans=='y' || ans=='Y');
getch();
}

Você também pode gostar