please also put commends, thank you! Problem 2 Write a program: l. Generate a on
ID: 3669235 • Letter: P
Question
please also put commends, thank you!
Problem 2 Write a program: l. Generate a one dimensional array of integers by using random number generator, integers should be in [0,701; the array size should be 20 2. Let the user input number to be searched, if you can use binary search in the array? If so, use binary search function to search the number in the array, If not, explain why, fix it and then use binary search function to search the number in the array. 3. The function should accept one array and a number to search for. If the number is found (if there are duplicate numbers, get the first one), print out the number and "Number found!", and output the original position. If not print out "Number isn't found 4. You may use data structure for the array, and you may use other pointer or index for arrayExplanation / Answer
Answer - In below program as numbers are genrated randomly, so it may we unsorted array that is why we weren`t able to use binary search. Therefore to solve the issue, we are using buble sort in main program to sort the randomly generated array and then passing it to the search function.
#include <iostream>
#include <cstdlib> /* srand, rand */
//#include <time>
using namespace std;
void Search(int a[20],int num)
{
int position,lowerbound=1,upperbound=20;
position = ( lowerbound + upperbound) / 2;
while((a[position] != num) && (lowerbound <= upperbound))
{
if (a[position] > num) // If the number is > number to search, ..
{ // decrease position by one.
upperbound = position - 1;
}
else
{ // Else, increase position by one.
lowerbound = position + 1;
}
position = (lowerbound + upperbound) / 2;
}
if (a[position]==num)
{
cout<<" Number "<<num<<" found at "<<position<<"th position";
}
else
{
cout<<" Number "<<num<<" is not found";
}
}
int main() {
int arr[20];
int rand_num,num_search;
srand (time(NULL)); /* initialize random seed: */
for(int i=1;i<=20;i++)
{
rand_num = rand() % 70 + 0; /* generate secret number between 0 and 70: */
arr[i]=rand_num;
}
cout<<" Array genrated randomly : ";
for(int i=1;i<=20;i++)
{
cout<<" "<<arr[i];
}
cout<<" Enter number to Search : ";
cin>>num_search;
for(int i=1;i<20;++i)
{
for(int j=0;j<(20-i);++j)
if(arr[j]>arr[j+1])
{
int temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
Search(arr,num_search); /* search funtion call */
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.