In this lab, we are going to practice writing template functions . This should b
ID: 645728 • Letter: I
Question
In this lab, we are going to practice writing template functions. This should be pretty easy.
You will be converting the quicksort function into a template version (see lecture 8 for quicksort reference). And this template version of quicksort function should be able to work with different data types. In this lab, we are going to use both std::list and std::vector.
Note 1: DO NOT copy and paste the quicksort algorithm directly from the slides, and PLEASE type everything yourself!
Note 2: Since now the template quicksort function is generic for both list and vector, when you traverse the elements inside a list or a vector using iterators, you should probably use std::advance instead of the + or += operator, because the latter only works with random access iterators (although std::advance(iterator, 1) and ++iterator do the same thing).
Note 3: Don't forget to #include <list> and #include <algorithm> if you are going to use std::list and std::advance.
Here is the example output:
After sorting vector v = {5, 1, 4, 2, 8, 18, 3, 33} and list l = {23, 14, 31, 57, 28, 49}:
./Lab8
The sorted vector is:
1 2 3 4 5 8 18 33
The sorted list is:
14 23 28 31 49 57
Explanation / Answer
#include #include //needed for swap() function using namespace std; // Function prototypes template T quickSort(T [], int, int); template T partition(T [], int, int); int main() { // Array to be sorted. const int SIZE = 10; int array[SIZE] = {100, 35, 7, 21, 89, 10, 148, 983, 33, 29}; // Echo the array to be sorted. for (int k = 0; kRelated Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.