Write a program that prompts the user to enter the number of elements and the nu
ID: 3629099 • 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:
ii) Include a function called by main to implement the binary search.
The ordered array produced by the sort should be passed to the search
routine which returns the location in the sorted array of the sought value,
or -1 if the value is not in the array.
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.