***data in the file are in ascending order. load them from inputfile into an arr
ID: 3638663 • Letter: #
Question
***data in the file are in ascending order. load them from inputfile into an array containing 5000 elements***implement the search such that it will be called 3 times, each with a different "size" array. The 3 "sizes" will be 1,000 elements to search, 2500 elements to search, 5000 elements to search. When you implement the algorithm, include a “search” counter that will keep track of how many comparisons were performed to find a number. After a search is performed, display and/or write to file two pieces of information.
1.Whether or not the searched-for number was found.
2.How many comparisons were made in the process. Show the number of comparisons made even if the searched-for number has not been found!
Explanation / Answer
please rate - thanks
#include <iostream>
#include <fstream>
using namespace std;
void search(int[],int,int);
int main()
{
int num[5000],i,key,max=5000;
ifstream in;
in.open("input.txt"); //open file
if(in.fail()) //is it ok?
{ cout<<"input file did not open please check it ";
system("pause");
return 1;
}
for(i=0;i<max;i++)
{in>>num[i];
}
cout<<"Enter number to search: ";
cin>>key;
search(num,key,1000);
search(num,key,2500);
search(num,key,5000);
system("pause");
return 0;
}
void search(int n[],int key,int max)
{int low=0,mid,count=1;
cout<<"numbers searched: "<<max<<endl;
while(low<=max )
{mid=(low+max)/2;
if(n[mid]<key)
{ low = mid + 1;
count++;
}
else
{if( n[ mid ]>key )
{max = mid - 1;
count++;
}
else
{cout<<key<<" found at index "<<mid<<endl;
cout<<count<<" comparisons made ";
return;
}
}
}
cout<<key<<" not found "<<endl;
cout<<count<<" comparisons made ";
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.