Question
Problem: I am trying to implement a binary search function in C++. I am trying to carry out the same 10,000,000 unsuccessful searches for eight
Problem:
I am trying to implement a binary search function in C++. I am trying to carry out the same 10,000,000 unsuccessful searches for eight different-sized arrays, namely arrays of sizes 128, 512, 2048, 8192, 32768, 131072, 524288, and 2,097,152. Measure in each of the three programs the time it takes to do the 10,000,000 searches for each of the eight arrays.
Please correct all errors. Add/edit please!
My program:
#include "header.h" #include
bool binary_search(int* array, int key, int first, int last);
int main() { clock_t start, end; int size = 2097152; int* array = new int[size]; for (int i = 0; i < size; i++) { array[i] = 0; } start = clock(); for (int = 0; i < 10000000; i++) { binary_search(array, 1, 0, size); } end = clock();
double time = double(end - start) / CLOCKS_PER_SEC; cout << "Search time is: " << time << endl;
system("pause"); }
bool binary_seach(int* array, int key, int first, int last) { bool found = false;
while (first <= last && !found) { int mid = (first + last) / 2; //mid = half the current array if(array[mid] == key) { found = true; } else if(array[mid] < key) //if word is less than the key, then first = mid + 1 { first = mid + 1; } else //if word is bigger than the key, then the last = mid - 1 { last = mid - 1; } } return found; }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started