No Description

search.cpp 1.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. // Measure execution times of binary search and linear search
  2. // on a sorted list.
  3. //
  4. // Usage:
  5. // ./<exec name> <size of list>
  6. #include <iostream>
  7. #include <vector>
  8. #include <cstdlib>
  9. #include <algorithm>
  10. using namespace std;
  11. int main(int argc, char *argv[]) {
  12. // get the command line arguments
  13. if (argc < 2) {
  14. cout << "Usage: " << argv[0] << " <size> \n";
  15. exit(1);
  16. }
  17. int size = atoi(argv[1]);
  18. vector<int> v;
  19. // fill the v vector with random integers and then sort
  20. for (int i = 0; i < size; i++) v.push_back(rand());
  21. sort(v.begin(), v.end());
  22. // initialize the random seed
  23. srand(time(NULL));
  24. int search_item;
  25. double elapsed_secs;
  26. clock_t begin = clock();
  27. // do a 100k searches using binary search
  28. for (int i = 0; i < 100000; i++) {
  29. search_item = rand();
  30. binary_search(v.begin(), v.end(), search_item );
  31. }
  32. clock_t end = clock();
  33. elapsed_secs = static_cast<double>(end - begin) / CLOCKS_PER_SEC;
  34. cout << "\nBinary search: " << elapsed_secs << " seconds\n";
  35. begin = clock();
  36. // do 1000 searches using linear find.
  37. for (int i = 0; i < 1000; i++) {
  38. search_item = rand();
  39. find(v.begin(), v.end(), search_item);
  40. }
  41. end = clock();
  42. elapsed_secs = static_cast<double>(end - begin) / CLOCKS_PER_SEC;
  43. cout << "Linear search: " << elapsed_secs << " seconds\n\n";
  44. return 0;
  45. }