Continuing from last time, we'll consider another potential implementation of a set, this time based on an underlying array that is kept in sorted order. The addition of a sorting invariant means some of our functions are more complicated (i.e. you can't just put elements wherever), but searching for elements in the array can be done much more efficiently.
Finally, it makes sense to introduce templates as a miscellaneous topic here. In particular, templates can be used to implement generic containers with flexible element types (e.g. set<int>
and set<string>
). Generally speaking, they also complete our exploration (started a few lectures ago) of different kinds of polymorphism.
1: Time Complexity
1.1
As we're asessing the fitness of a data structure for a given task, it's helpful to determine its time complexity, which quantifies how well it performs as the size of the data we're working with scales up. Recall two key types of time complexity:
1.1 Exercise: Time Complexity
Recall the unsorted
Below are several implementations of functions for the unsorted
You're welcome to check your solution with this walkthrough video: |
2: A Sorted
2.1
IntSet
Let's make a key change to the fundamental strategy and data representation for our set - keeping all the elements in sorted order - and see if we can improve the performance of the data structure…
2.1 Exercise:
SortedIntSet::insert()
Implement the The You're welcome to check your solution with this walkthrough video: Note: This walkthrough uses several different files for the code, which is different than the above, where we had everthing embedded into one file. (The solution for |
3: Templates
3.1
Finally, let's use templates to implement a generic set container with a flexible element type.
3.1 Exercise:
fillFromArray() Function Template
Fill in the blanks to make the function work as intended (the
You're welcome to check your solution with this walkthrough video: |