Write a program that prompts the user to enter the number of elements and the nu
ID: 3629098 • Letter: W
Question
Write a program that prompts the user to enter the number of elements and thenumbers themselves to be placed in an integer array that holds a maximum of 50
elements.
The program should then prompt the user for an integer which will be
searched for in the array using a binary search. Make sure to include the following
steps along the way:
i) A sort routine must be called before the binary search. You may use either
the selection sort or the bubble sort. However, the sort must be implemented
in its own function and not in main.
Explanation / Answer
please rate - thanks
#include <iostream>
using namespace std;
void sort(int[],int);
int binarysearch(int[],int,int);
int main()
{int numbers[50],n,i,key,val;
cout<<"How many numbers do you have? (max 50): ";
cin>>n;
for(i=0;i<n;i++)
{cout<<"Enter number "<<i+1<<": ";
cin>>numbers[i];
}
sort(numbers,n);
cout<<"Enter the number to search for: ";
cin>>key;
val=binarysearch(numbers,n,key);
if(val<0)
cout<<key <<" was not found ";
else
cout<<key<<" was found at location "<<val<<endl;
system("pause");
return 0;
}
void sort(int a[],int n)
{int i,j,t;
for(i=0;i<n-1;i++)
for(j=i;j<n;j++)
if(a[i]>a[j])
{t=a[i];
a[i]=a[j];
a[j]=t;
}
}
int binarysearch(int a[],int n,int key)
{int low=0,max=n,mid;
while(low<=max )
{mid=(low+max)/2;
if(a[mid]<key)
low = mid + 1;
else
{if(a[mid]>key )
max=mid-1;
else
{return mid;
}
}
}
return -1;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.