#include #include #include #include #include #include using namespace std; // these two allow you to get the time spent // Create an instance of the class. // Call Start // Run your code // Call Stop // Call Time with the appropriate unit. // // See DoExperiment below // enum class TimeUnitT {MINUTE, SECOND, MILLISECOND, MICROSECOND, NANOSECOND}; class TimerT { public: void Start(){ start = chrono::high_resolution_clock::now(); } void Stop(){ end = chrono::high_resolution_clock::now(); diff = end - start; } double Time(TimeUnitT u) { using namespace chrono; switch (u) { case TimeUnitT::MINUTE: return duration>{diff}.count(); case TimeUnitT::SECOND: return duration>{diff}.count(); case TimeUnitT::MILLISECOND: return duration{diff}.count(); case TimeUnitT::MICROSECOND: return duration{diff}.count(); case TimeUnitT::NANOSECOND: return duration{diff}.count(); default: return 0; } } private: std::chrono::time_point start, end; std::chrono::duration diff; }; const int MAX_VALUE{1'000'000}; const int MAX_TRIALS{10}; void DoExperiment(int size); bool Check(const vector & data); int GetRandomNumber(); void SelectionSort(vector & data); int GLOBALCompares; int GLOBALMoves; int main() { cout << "Sort,Size,Time,Compares,Moves" << endl; for (int trialSize = 1'000; trialSize <= 10'000; trialSize+= 1'000) { for(int trial = 0; trial < MAX_TRIALS; ++trial) { DoExperiment(trialSize); } } return 0; } // generate a random number between 0 and MAX_VALUE // Just call the function. // The first time will initialize the structures // These will be used on future calls. int GetRandomNumber(){ static random_device rd; // this initializes the RNG static mt19937 gen(rd()); // This uses the RNG to generate a number in the distribution. static uniform_int_distribution <> distrib(0, MAX_VALUE); return distrib(gen); } // Check to see if an array is in order. bool Check(const vector & data){ bool good{true}; for (size_t i = 1; i < data.size(); ++i) { if (data[i] < data[i-1]) { good = false; } } return good; } void DoExperiment(int size){ vector data; for(int i = 0; i < size; ++i) { data.push_back(GetRandomNumber()); } TimerT timer; // reset compares and moves counter GLOBALCompares = 0; GLOBALMoves = 0; // start the wall clock timer. timer.Start(); SelectionSort(data); timer.Stop(); if (not Check(data)) { cout << "Sort failed " << endl; } double time = timer.Time(TimeUnitT::MILLISECOND); // output a line for the CSV file. cout << fixed << setprecision(2); cout << "selection," << size << "," << time << "," << GLOBALCompares << "," << GLOBALMoves << endl; } // my implementation of selection sort. void SelectionSort(vector & data){ for(size_t current = 0; current < data.size(); ++ current) { size_t small{current}; for(size_t j = current+1; j < data.size(); ++j) { ++GLOBALCompares; if (data[small] > data[j]) { small = j; } } if (small != current ) { GLOBALMoves += 2; swap(data[small], data[current]); } } }