暫無描述

sorting.cpp 1.7KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. // Measure execution times of bubble sort vs. the STL implementation
  2. // of sort.
  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. //
  12. // Given a vector if ints, bubble sort it.
  13. //
  14. void bubbleSort(vector<int> & arr) {
  15. int i, j;
  16. int n = arr.size();
  17. for (i = 0; i < n-1; i++) {
  18. // Last i elements are already in place
  19. for (j = 0; j < n-i-1; j++) {
  20. if (arr[j] > arr[j+1])
  21. swap(arr[j], arr[j+1]);
  22. }
  23. }
  24. }
  25. int main(int argc, char *argv[]) {
  26. if (argc < 2) {
  27. cout << "Usage: " << argv[0] << " <size> \n";
  28. exit(1);
  29. }
  30. int size = atoi(argv[1]);
  31. vector<int> v,w;
  32. // initialize the random seed
  33. srand(time(NULL));
  34. // fill the v vector with random integers
  35. for (unsigned int i = 0; i < size; i++)
  36. v.push_back(rand() % size);
  37. // copy v to w
  38. w = v;
  39. double elapsed_secs;
  40. // measure time to bubble sort
  41. clock_t begin = clock();
  42. bubbleSort(v);
  43. clock_t end = clock();
  44. elapsed_secs = static_cast<double>(end - begin) / CLOCKS_PER_SEC;
  45. cout << "\nTime elapsed for Bubblesort: " << elapsed_secs << " seconds\n";
  46. // measure time to sort using the STL sort algorithm
  47. begin = clock();
  48. sort(w.begin(),w.end());
  49. end = clock();
  50. elapsed_secs = static_cast<double>(end - begin) / CLOCKS_PER_SEC;
  51. cout << "Time elapsed for STL sort: " << elapsed_secs << " seconds\n";
  52. if ( is_sorted(v.begin(),v.end()) && is_sorted(w.begin(),w.end()) )
  53. cout << "Congrats! Both vectors were properly sorted!\n\n";
  54. else
  55. cout << "At least one of the algorithms returned an unsorted vector.\n\n";
  56. return 0;
  57. }