Advertisement
jkavart

Untitled

Feb 12th, 2018
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.73 KB | None | 0 0
  1. #include <cstdlib>
  2. #include <time.h>
  3. #include <iostream>
  4. #include <string>
  5.  
  6. using namespace std;
  7.  
  8.  
  9. int binarySearch(const int list[], int length,
  10. const int& item)
  11. {
  12.     int first = 0;
  13.     int last = length - 1;
  14.     int mid;
  15.     bool found = false;
  16.     while (first <= last && !found)
  17.     {
  18.         mid = (first + last) / 2;
  19.         if (list[mid] == item)
  20.             found = true;
  21.         else if (list[mid] > item)
  22.             last = mid - 1;
  23.         else
  24.             first = mid + 1;
  25.     }
  26.     if (found)
  27.         return mid;
  28.     else
  29.         return -1;
  30. }
  31. void loopTime(int array[],int sizeOfArray)
  32. {//takes an array and its size as paramaters and loops it 10mill times
  33.     clock_t timeStart; //and times the loop in seconds
  34.     timeStart = clock();
  35.     for(int i=0;i<1000000;i++)
  36.     {
  37.         binarySearch(array,sizeOfArray,2);
  38.     }
  39.     cout<<"Time "<<((((double)clock()-timeStart))/CLOCKS_PER_SEC)
  40.             <<" in seconds of size "<<sizeOfArray<<endl;
  41. }
  42. void buildAndTestArray(const int SIZE)
  43. {//builds an array and inputs it into loopTime()
  44.     int arr[SIZE];
  45.     for(int i=0;i<SIZE;i++)
  46.     {
  47.         arr[i]=0;
  48.     }
  49.     loopTime(arr,SIZE);
  50. }
  51. int main()
  52. {
  53.    
  54.     const int size128=128;
  55.     const int size512=512;
  56.     const int size2048=2048;
  57.     const int size8192=8192;
  58.     const int size32768=32768;
  59.     const int size131072=131072;
  60.     const int size524288=524288;
  61.     const int size2097152=2097152;
  62.     buildAndTestArray(size128);
  63.     buildAndTestArray(size512);
  64.     buildAndTestArray(size2048);
  65.     buildAndTestArray(size8192);
  66.     buildAndTestArray(size32768);
  67.     buildAndTestArray(size131072);
  68.     buildAndTestArray(size524288);
  69.     buildAndTestArray(size2097152);
  70.    
  71.     return 0;
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement