223 test 2 Flashcards
declare a normal vector vs ptr
int* xptr = &x ; // & is the “ address of” operator
Dynamically allocating memory at runtime
int* yptr = new int; // allocate new memory on the fly
- yptr = 96;
memory leaks
you have memory that nothing can access
rule of three
A class that defines a destructor, assignment operator, or a copy constructor should define all three
Dereferencing
a pointer accesses value at the pointer’s stored address
* xptr = 57; // * here is the “ dereference “ operator
binary search
Iteratively search for a value v in a non-empty sorted list
- Pick the middle item in a list
- If middle item > v, then search in left half of list
- If middle item < v, then search in right half of list
- If middle item == v, then found match
What is the worst case for binary search?
Keep searching (halving list) until one element left)
Assume T(n) = 27, which is O(1)
• In this case, pick n0 to be 0 (any value will work in this case)
• Pick k to be 27, giving:
0 ≤ 27 ≤ 27 · 1 for k = 27 and all n ≥ 0
Assume T(n) = 3n + 2, which is O(n)
There are lots, but lets pick k = 5 and n0 = 1, giving:
• 3n + 2 ≤ 5n for all n ≥ 1
• e.g., 3 · 1 + 2 ≤ 5, 3 · 2 + 2 ≤ 10, 3 · 3 + 2 ≤ 15, etc.
Assume T(n) = n^2 − 5n + 10,
What values of n0 and k do we pick to solve this?
• There are lots, but lets pick n0 = 2 and k = 4, giving:
• n
2 − 5n + 10 ≤ 4n
2
for all n ≥ 1
• Note: T(2) = 4 − 10 + 10 = 4 ≤ 4 · 2
Selection Sort
The basic idea • Select (i.e., “find”) the largest item • Swap it with the last item in the list • Repeat with items 0 to n − 2 • Stop when only one item left
selection sort best and worst case
best: n^2
worst: n^2
bubble sort
The basic idea Compare adjacent items Swap if out of order Repeat with items 0 to n − 2 Stop when only one item left
bubble best and worst
best O(n) worst O(n^2)
(Linear) Insertion Sort
(Linear) Insertion Sort
The basic idea (note: beginning of list is sorted, rest is unsorted)
• Select first item (in unsorted region)
• Insert item into correct position in sorted region (shifting larger items over)
• Stop when unsorted region is empty
best and worst insertion sort
Best case: List already sorted (no shifts, just n-1 passes)
• Worst case: List in reverse order (shift max number of times each pass)
best O(n) worst O(n^2)
merge sort
The basic idea (note: recursive “divide and conquer” approach)
• divide list into two halves
• sort each half (recursive step)
• merge the sorted halves into sorted list