C++ Write a menu driven program that has at least two functions (searchList and
ID: 3669372 • Letter: C
Question
C++
Write a menu driven program that has at least two functions (searchList and binarySearch) and will allow the user to:
- insert 10 integer items into an array
- choose a search option (1- linear, 2- binary, 0 - exit)
- search the array for a value entered buy the user
- include for option 2- binary search two additional submenus (b- bubble sort, and s – selection sort) that allows the user to choose the sorting method prior to binary search. The sorted array should be displayed and then the user should be allowed to choose a search value
- allows the linear search to show ALL locations of the search value (this will require you to make some changes to the linear search function)
- includes input validation for correct menu options
Explanation / Answer
#include<iostream>
#include<stdio.h>
using namespace std;
int linearsearch(int a[20],int key,int n);
int binarysearch(int a[20],int key,int n);
int main()
{
int a[20],k,n,ch,ans,i;
cout<<"Enter the total number of elements ";
cin>>n;
while(1){
cout<<" Menu ";
cout<<"1.linear search ";
cout<<"2.binary search ";
cout<<"3.exit ";
cout<<"Enter your choice ";
cin>>ch;
switch(ch){
case 1:
cout<<"Enter the elements ";
for(i=0;i<n;i++){
cin>>a[i];
}
cout<<"Enter the key elememts ";
cin>>k;
ans=linearsearch(a,k,n);
if(ans!=-1)
cout<<"element "<<k<<" is found ";
else
cout<<"Element "<<k<<" is not found ";
break;
case 2:
cout<<"Enter the elements ";
for(i=0;i<n;i++){
cin>>a[i];
}
cout<<"Enter the key elememts ";
cin>>k;
ans=binarysearch(a,k,n);
if(ans!=-1)
cout<<"element "<<k<<" is found ";
else
cout<<"Element "<<k<<" not found ";
break;
case 3:
exit(0);
default:
cout<<"Invalid entry ";
}
}
}
int linearsearch(int a[20],int key,int n)
{
int i;
for(i=0;i<n;i++){
if(key==a[i])
return i;
}
return -1;
}
int binarysearch(int a[20],int key,int n)
{
int high,low,mid;
low=0;
high=n-1;
while(low<=high){
mid=(low+high)/2;
if(a[mid]==key)
return mid;
else if(a[mid]<key)
low=mid+1;
else
high=mid-1;
}
return -1;
}
OUTPUT:
output :
Enter the total number of elements
5
Menu
1.linear search
2.binary search
Enter your choice
1
Enter the elements
1 5 6 7 4
Enter the key elememts
7
element 7 is found
Menu
1.linear search
2.binary search
3.exit
Enter your choice
1
Enter the elements
55 66 77 88 99
Enter the key elememts
100
Element 100 is not found
Menu
1.linear search
2.binary search
3.exit
Enter your choice
2
Enter the elements
15 55 66 44 22
Enter the key elememts
55
element 55 is found
Menu
1.linear search
2.binary search
3.exit
Enter your choice
2
Enter the elements
55 66 45 56 23
Enter the key elememts
100
Element 100 not found
Menu
1.linear search
2.binary search
3.exit
Enter your choice
3
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.