Data Structures Exam 1 Review
Priority Queue
A priority queue has a highest priority, first out protocol
What is an Algorithm?
A self-contained step-by-step set of operations to be performed
Binary Search
An ordered list is divided in 2 with each comparison. ---Requires the sequence to be sorted ---More efficient!
What are APIs?
Application Programming Interface ---ADTs + syntax Function prototypes for all accessible functions constructors are usually listed separately Description of methods, sometimes with pre- and post-conditions Complexities (sometimes, not always required/necessary) NOTE: does not expose implementation details
complexity breakdown
Best case, average, and worse case.
C++ array class
C++ array is more flexible than plain array, but not as flexible as a vector Size is still fixed at time of its declaration Two template parameters: type and size
programs are ______ _______ + _________
Data Structures + Algorithms
Insertion Sort
Each items is take in turn, compare to the items in a sorted list and placed in the correct position.
What is the rule of three?
If you have one of these, you must create the rest Destructor ~Class(); Copy Constructor Class (Class const&); Copy Assignment Class& operator= (Class const&);
Interpolation Search
Knowing the upper and lower limits of a sorted range, we can: Estimate the position of a "key" Obtain better performance if the data is uniformly distributed ie: opening a certain section of the dictionary
Binary Search
Looking for an item in an already sorted list by eliminating large portions of the data on each comparison
Big-O notation
Machine-independent means for specifying efficiency (complexity) Concerned with *asymptotic behavior count key operation using growth or runtime function example: if T(N)= 9N^2 + 43N + 7 then the algorithm is O(N2)
bubble sort
Moving through a list repeatedly, swapping elements that are in the wrong order.
Bubble Sort Best case
O(N)
Algorithm Details
Operations on data Insertion and removal of elements Rearranging data (reverse, sort, merge) Searching data
Given a Point class with double "x" and "y" fields, write a default constructor that initializes x and y both to 0. You must use a member initializer list to receive any credit.
Point () : double x = 0; , double y = 0; { }
How do you convert a pointer to a reference? A reference to a pointer?
Pointer dereference operator * - Always takes a pointer and returns a reference T& operator** (T ** ptr); Reference "addressof" operator & -Always takes a reference and returns a pointer T* operator& (T& ptr);
What's the difference between a reference and a pointer?
Pointers: A pointer is a variable that holds memory address of another variable. A pointer needs to be dereferenced with ** operator to access the memory location it points to. --get value at... References : A reference variable is an alias, that is, another name for an already existing variable. ---get value of...
Types of searching
Sequential Selection Bubble Sort Insertion Binary Search Interpolation
Examples of Algorithms
Sequential search, binary search Bubble sort, selection sort, merge sort Inserting an element into a Binary Search Tree
Can you always perform interpolation search? Why or why not?
can't be used on data that isn't uniformly spaced apart
What is an abstract data type?
collection of values (e.g. ints, Persons, Lists) --Use ADT to specify a type set of operations on the data with pre- and post- conditions Typically implement ADTs with a class
Declare a variable called refA which is a const-reference to an int originally referred to by the expression "A[4]"
const int & refA= A[4];
array, vector, and deque run in
constant time
how are algorithms, containers, and iterators related?
containers -->>> are used to extract iterators ---->> which are fed to algorithms containers --/->> can't be directly used in algorithms
A class encapsulates two things:
data (data members {Java: instance variables}) operations (member functions {Java: methods})
whenever you use new you must use ______ or else you could cause a ________
delete.....memory leak
Binary search midpoint equation
first + ((last-first)/2)
Describe how to resize a vector. Consider all three cases.
if new size if the same as size do nothing if new size is greater than size, set size to new size if new size is less than size, push_back values until size is new size
Describe the relationship between new/delete and Constructors/Destructors
if you have a new you need a corresponding delete if you have a constructor you need a Destructors both rules are for memory clearing
what is the rule of five?
if you implement any of the following five special functions, you must implement all of them" Destructor ~Class(); Copy Constructor Class (Class const&); Copy Assignment Class& operator= (Class const&); Move Constructor Class (Class&&); Move Assignment Class& operator= (Class&&);
Which vector operations are slow?
insert at the beginning
Syntax for sequential containers
insert, front, back.
Give a reason for preferring insertion sort over selection sort.
insertion sort will perform less comparisons than selection sort, depending on the degree of "sortedness" of the array. While selection sort must scan the remaining parts of the array when placing an element, insertion sort only scans as many elements as necessary. when the array is already sorted or almost sorted, insertion sort performs in O(n) time.
Write a declaration for a function called "minLoc" that returns a pointer-to-int and accepts a vector of ints passed by const reference.
int* minLoc (vector<int>& const);
Why would you want to use linear search instead of binary search?
linear search can be used with non sorted data, while data must be sorted for binary search
map
map maintains a collection of key-value pairs
every _______ member function has a pointer to the invoking object
non-static
C++ Containers
provides 16 container classes implementing ADTs with various data structures
Syntax for Adaptive containers
push, pop, top, back,delete, front
polynomial algorithms
quadratic O(N^2) --only practical for relatively small values of N cubic O(N^3) --efficiency is generally poor
What is Time Complexity?
relate operations to input size aka how long it takes to run a function
What is Space Complexity?
relates number of bytes to input size
Selection Sort
repeatedly scans for the smallest item in the list and swaps it with the element at the current index. The index is then incremented, and the process repeats until the last two elements are sorted.
Give a reason for preferring selection sort over insertion sort.
selection sorts number of writes (swaps) is in O(n), while in insertion sort it is in O(n^2).
Describe how to insert a node between two nodes in a doubly-linked list. Diagram / pseudocode
set new nodes prev to left node and next to right node set the node to the lefts next to the new node set the nodes to the rights prev to the new node increment size
stack
stack allows access only at one end of the sequence, called top
class template
template <typename T1, typename T2, ...> class ClassName { ... };
.size() vs ->size
use -> when using pointers and function calls, don't use .
What is a type alias?
use a variable to reference a pointer rather than the pointer syntax using IntPtr = int*; using IntRef = int&; // now we can use IntPtr instead of int** or IntRef instead of int&
Adapter Containers
use sequence container as underlying storage Design Pattern: Adapter (Adapter's interface provides a restricted set of operations) stack, queue, priority_queue
Vector
vector overcomes the limitations of array Dynamically resizable Know their length and capacity Elements still stored contiguously -- O(1) element access Easily copied
what is constant time?
when an algorithm's complexity is independent of the input size O(1) ex: vector pushback
what is linear time?
when an algorithm's runtime is proportional to input size O(N) ex: sequential min element search
What is iterator invalidation? How do you fix iterator invalidation?
when an iterator is lost after a command is completed save the position of the iterator and re-establish it after the invalidation occurs
matrix
2D array [row][column]
Why would you prefer a vector over a list? Give at least three reasons.
(Vector Advantages) random access in constant time data is contiguously stored in memory low storage overhead
why would you prefer a list over a vector? Give at least three reasons.
(Vector disadvantages) insertion and removal at the end iterator invalidation easily reference prev and next
Data Structures Details
(efficient) storage and manipulation of (large) data sets Arrays (both static and dynamic), linked lists, linked trees Used to implement abstract data types e.g. set, list efficient) storage and manipulation of (large) data sets
implement copy constructor for vector
// Copy ctor. // Initialize this object from "a". Vector (const Vector& a) : m_size(distance (a.begin(),a.end())) , m_capacity (m_size) , m_array (new T[m_capacity]) { copy (a.begin(), a.end(), begin()); }
Implement the range constructor for vector
// Range ctor. // Initialize an Array from the range [first, last). // "first" and "last" must be Array iterators or pointers // into a primitive array. // remember to use a member initializer list! Vector (const_iterator first, const_iterator last) : m_size(distance (first,last)) , m_capacity (m_size) , m_array (new T[m_capacity]) { copy (first, last, begin()); }
Implement the size constructor for vector
// Size ctor. // Initialize an Array of size "pSize", with each element // set to "value". Vector (size_t pSize, const T& value = T ()) : m_size (pSize), m_capacity (pSize), m_array (new T[m_capacity]) { fill (begin (), end (), value); }
Binary Search steps
0) If the array is empty, return not found 1) Look at the middle element. If a match, return location ---If target smaller, search left sub-array ---If target larger, search right sub-array repeat
Types of Complexity
1) Speed -relate operations to input size 2) Space - relates number of bytes to input size example: space for linked list of ints vs array of ints
What is a Data Structure?
A particular way of organizing data in a computer so that it can be used efficiently
set
A set maintains a collection of unique values called keys
What's the worst-case complexity of bubble sort? Selection sort? Insertion sort?
All O(N^2) --interpolation is O(N)
Range Notation:
Array A has valid indicies in the range of 0 (inclusive) to N (exclusive) A[0..N) Range notation is useful when we want to SPLIT or JOIN ranges: A[0..N) <=> A[0..m) A[m..N)
What does a constructor do?
Initializes the object to some defined state --Called during new
Why would you want to use interpolation search over binary search?
Interpolation search works better than Binary Search for a sorted and uniformly distributed array. binary search always starts from the middle, while interpolation starts at a point near the wanted value
What does a destructor do?
Is supposed to relinquish any owned resources the of "deleted" object --Called during delete
Given a code segment, determine T(N) when counting comparisons. Then give O(N) for (int i = 0; i < 4; ++i) for (int j = 4; j >= 0; --j) if (A[i] != A[j]) ...
T(N)= O(N)= O(N^2)?
interpolation worst case
O(N)
interpolation average case
O(log^2 N)
Insertion sort best case
O(n)
Bubble Sort Worst case
O(n^2)
Insertion Sort Worst Case
O(n^2)
Selection Sort Worst and Best Case
O(n^2)
Examples of Data Structures
Primitive types: bool, char, short, int, etc. Composite types: array, struct/class, union Abstract Data types: stack, queue, list, set, map
What does it mean to have a const member function? Why would we want to mark a member function as const?
The idea of const functions is not to allow them to modify the object on which they are called. so that accidental changes to objects are avoided.
C++(passing by value)
This is passing a value straight in without referencing to it within mode semantics, using this way of passing means you can change the items transferred in. aka alters the original ex: doSomething(int x, inty)
C++( passing by reference)
This is passing a value via reference or by aliasing. this version of passing parameters uses in/out semantics **doesn't allow you to change the original variable for the whole program just the method. aka makes a copy, the original is not changed ex: doSomething(int &x, int &y)
What is the time complexity of {insertion,removal} operation for a {vector,list} at the {beginning,arbitrary,end}? (this is actually 12 questions in one)
Vector insert and erase: begin- O(n), arbMid- O(n), end- O(1) List insert and erase: begin, arb middle, end *ALL O(1)*
Vector/Array Iterators vs Lists Iterators
Vector/Array iterator IS A POINTER List iterator HAS A node pointer
vector benefits
Vectors allow efficient sub-scripting: O(1) Position-based indexing (why it's called a sequence container)
What is an Iterator?
a high-level abstraction of a value stored in a container
What is nullptr?
a pointer that points to nothing
Associative Containers
access elements based off their key -- O(1) to O(lg(N)) may bear no relationship to where it's stored (unordered_)(multi)set, (unordered_)(multi)map
Sequence Containers
access elements based off their position -- O(1) to O(N) index starts at zero array, vector, list, forward_list, deque
Algorithm examples
accumulate copy sort lower_bound, upper_bound nth_element partition
What is the difference between new and new[] ?
new points to the first element in the array new[] points to the whole array
Container class examples
array, vector, deque, list, forward_list set, multiset, map, multimap unordered_set, unordered_multiset, unordered_map, unordered_multimap stack, queue, priority_queue string, valarray, bitset (container-like)
What is the difference between a bidirectional and random access iterator?
bidirectional iterators can be incremented and decremented random access iterators has all the features of bidirectional, but also provides constant-time methods for moving forward and backward in arbitrary-sized steps
function templates
can be used to make the function generic always comes at the very beginning of any function or class definition template <typename T>
Describe how to erase a node between two nodes in a doubly-linked list. Diagram / pseudocode
delete node set the lefts nodes next to the deleted right node set the right nodes prev to the left node decrement size
Which operations for vector will (sometimes) invalidate iterators? Provide at least three.
erase? resize? reserve
Sequential searching
examine 0th element, then 1st, and so on...
one iteration of _______________ could be slower than complete ______________
interpolation.....binary serach
Interpolation Search mid equation
mid = ( ( val - A[first] ) / ( A[last] - A[first] ) ) x (last-first) more costly than binary search --expensive division
queue
queue allows insertion to the back and removal from the front