//This program implements the well known Insertion Sort Algorithm //Note. The code was debugged by simulating it using playing cards // with toothpicks for iterators. #include #include #include #include #include void sort( vector::iterator begin, vector::iterator end) { vector::iterator sorted;//lowest sorted item for (sorted = end-1; sorted != begin; sorted--) { vector::iterator next = sorted-1;//put in place int value = *next; vector::iterator i; for (i = sorted; i != end; i++) { if (value <= *i) break; *next = *i; next++; } *next=value; }//for next } int main() { const int seed = static_cast(time(0)); srand(seed);//set random number differently each run const int Biggest = 100000; const int Size = 5000; const int Sample = 100; double total_time =0.0; for(int s = 0; s data; for(int i = 0; i< Size; i++) { data.push_back(rand()%Biggest); } time_t time1 = time(0); sort(data.begin(), data.end()); time_t time2 = time(0); total_time+= difftime(time2, time1); /* Debugging for(vector::iterator p=data.begin(); p!=data.end(); p++) { cout << *p << "\t"; } cout << "\n----------\n"; */ } cout << "Insertion Sort. Size =" << Size << ", mean time ="; cout << total_time /Sample; return 0; }