#include #include #include #include #include using namespace std; //Let n be size of V, V.size() //run time: O(n) (linear) void printList(vector &V) //run time: O(1) { //run time of loop: #loops*costOfBody = n*O(1) = O(n) for (int i = 0; i < V.size(); i++) //#loops: n cout << V[i] << endl; //O(1) } //find and return the index of the smallest //item within the given range. //Let n be size of search range, n = end - start+1. //run time: O(1)+O(1)+O(n)+O(1)= O(n) (linear) int findSmallest(vector &V, int start, int end) //O(1) { int smallestSoFar = start; //O(1) //run time loop: n*O(1) = O(n) for (int i = start; i <= end; i++) //#loops: n { if (V[i] < V[smallestSoFar]) //O(1) smallestSoFar = i; } return smallestSoFar; //O(1) } //Let n = X.size() //Run time: O(1)+O(n^2) = O(n^2) void selectionSort(vector &X) //O(1) { //run time: n*(O(n)+O(1))= n*O(n)+n*O(1)=O(n^2)+O(n)= O(n^2) for (int i = 0; i < X.size(); i++) //#loops: n { int smallIndex = findSmallest(X, i, X.size() - 1); //O(n) swap(X[i], X[smallIndex]); //O(1) } } //Use a "heap" to sort a given //vector of numbers. //run time: O(n log n) void heapSort(vector& V) //O(1) { priority_queue H; //a heap //Step 1: put all the items into the heap //run time: n*O(log n) = O(n log n) for (int i = 0; i < V.size(); i++) //#loops: n H.push(V[i]); //O(log n) //Step 2: extractMax from heap until empty //run time: n*(O(1)+O(log n) = O(n log n) for (int i = 0; i < V.size(); i++) //#loops n { V[i] = H.top(); //O(1) H.pop(); //O(log n) } } int main() { vector X; X.push_back(15.3); //At index 0 X.push_back(8); //1 X.push_back(568); //2 X.push_back(45); //3 X.push_back(3.14); //4 X.push_back(93.7); //5 X.push_back(703); //6 X.push_back(57); //7 X.push_back(347.2); //8 X.push_back(1.5); //9 X.push_back(752); //10 X.push_back(57); //11 X.push_back(12); //12 X.push_back(53); //13 //Warmup: //Print the list printList(X); cout << endl; //Challenge #2: //Search list for smallest item: //return the index of smallest in specified range cout << findSmallest(X, 0, X.size() - 1) << endl; //9 cout << findSmallest(X, 5, 8) << endl; //7 cout << endl << endl; //Challenge #3 //Sort the list selectionSort(X); printList(X); //should now be sorted cout << endl; //Stress test with large list int huge = 1000000; vector bigList; for (int i = 0; i < huge; i++) bigList.push_back(rand()); auto start = chrono::high_resolution_clock::now(); //selectionSort(bigList); heapSort(bigList); auto finish = chrono::high_resolution_clock::now(); chrono::duration elapsed = finish - start; cout << "Algorithm took: " << elapsed.count() << endl; //printList(bigList); return 0; } ///Timing code /* auto start = chrono::high_resolution_clock::now(); //method to time... auto finish = chrono::high_resolution_clock::now(); chrono::duration elapsed = finish - start; cout << "Algorithm took: " << elapsed.count() << endl; */