Final Exam Cheat Sheet
Final Exam Cheat Sheet
(ADT) is a data type that isn't pre-defined in the programming language A collection is an object that is used to gather and organize other objects. Since it is an object, it
• An abstraction hides details to make a concept easier to manage An abstract data type is a data type whose values and operations are not inherently part of the has instance data and member methods. The instance data and member methods together
• All objects are abstractions in that they provide well-defined operations (the interface) programming language. It is abstract in that its implementation details should be hidden from define what the collection is and how the collection works. As an object, a collection is an
• They hide (encapsulate) the object's data and the implementation of the operations the user. A user interacts with the abstract data type through its interface, without knowing the abstraction, in that users interact with it through its interface, its public methods, without
• An object is a great mechanism for implementing a collection details of how the abstract data type is implemented. having to know anything about its instance data or how the methods work. By using the
A data type is a group of values and the operations defined on those values collection’s interface, users do not have to know the internals of how the collection is
implemented. } – indexed lists: numeric position in list, index updated every time list changes (java api likes this
• A data structure is the set of programming constructs and techniques used to implement a one). NEVEER a gap between elements
collection - To insert a node at the front of the list, first point the new node to the front node, - Find operation used used privately by remove, contains, and addAfter. RELIES on
declaration of a NumberValue object named num that will use Integer for its type. then reassign the front reference equal method.
NumberValue<Integer> num = new NumberValue<Integer>(); - List<E> interface (implemented by ArrayList and LinkedList classes)
- Array list implementation – shifting cant be avoided to O(n) can be used
Stack LIFO: - Linked List is the obvious choice. LinearNode is reused here as with queue and
- Array: bottom of array stack is 0, top integer indicates where the top of the stac kis and how stack. Head and tail references are maintained and an interger called count
many elements it has
- Array Push method: -
o public void push(T element) { Queue FIFO:
o if(count == stack.length) {
o T[] newStack = new T[stack.length*2];
o for(int i = 0; i < stack.length; i++)
o newStack[i] = stack[i];
o stack = newStack;
o } -
o - Common list operations
o stack[count++] = element; Array:
o }
- Linked Push method
o
o public void push(T element) {
o LinearNode<T> newNode = new LinearNode<T>(element);
o newNode.setNext(top);
o top = newNode; Java provides an interface named Queue. The LinkedList class is one of the classes that o
o count++; implements this interface. Though the interface is named Queue, the methods in the interface do
o } not use the names of the queue operations as described in the text. The Queue interface has Algorithms:
- Linked Peak: several methods that are similar to the queue operations but that have slightly different behaviors. The symbol omega (Ω) refers to a lower-bound function. Theta (Θ) refers to a function that
- public T peek() throws EmptyCollectionException Circular array enqueue establishes both an upper and a lower bound. Big-Oh notation, O( ), refers to an upper bound on
- { a growth function.
- if (isEmpty() )
public void enqueue(T element) {
- throw new Loops, nested loops, and calls to methods all contribute to the complexity of an algorithm
if(count == queue.length)
EmptyCollectionException("stack");
expandCapacity();
-
- T result = top.getElement();
queue[rear] = element;
- return result;
rear = (rear+1)%queue.length;
- }
count++;
o
}
- The API's stack class is derived from Vector, which has many non-stack abilities
Linked Enqueue
public void enqueue(T element) {
LinearNode<T> newNode = new LinearNode<T>(element);
Consider the following loop:
count = 1;
if(count == 0) while (count < n)
front = newNode; {
- else count *= 2;
- Maze TraversaL: rear.setNext(newNode); // some sequence of O(1) steps
o • An object representing a position in the maze is pushed onto the }
stack when trying a path The loop is executed log2n times, so the loop is O(log n)
o • If a dead end is encountered, the position is popped and another rear = newNode;
count++; The infix expression
path is tried
} (3 * 4 – (2 + 5)) * 4 / 2
Size method linked list queue no count variable is equivalent to the postfix expression
public int size() 34*25+–4*2/
{ linked list:
int count; Person current = first;
if (head == null) while (current != null)
count = 0; {
else System.out.println(current);
{ current = current.next;
count = 1; }
Linked List LinearNode<T> temp = head; // for traversal
sentinel node: Iterators:
while(temp.getNext() != null)
When adding and removing nodes from a linked list, the first node of the list is treated as a special {
case. This is because the list reference variable points to this node and will have to be adjusted if a An Iterable class is one that implements the Iterable interface. The Iterable interface has a single
count++; method, iterator, that returns an Iterator object. The returned object can be used to iterate over
node is added to or removed from the head. With the use of a dummy node, the reference to the temp = temp.getNext(); // go to next node
top of the list will never change (it will always refer to the dummy node), so the operations of objects of the class that implements the Iterable interface.
} // end while
adding and removing nodes can be simplified. } // end else
- Suppose myList is an ArrayList of Book objects
return count;
- don’t motify pointer unless inserting nodes or removing code. pointer should not } // end method size
be used to traverse list. Iterator<Student> it = roster.iterator();
Person current = first; while (it.hasNext() )
Lists: {
while (current != null) – ordered lists: ordered by inherent characteristic. “add” operation is particular to this.
{ it.next();
This study source was downloaded by 100000780412656 from CourseHero.com on - 04-12-2023 15:46:06
unordered list: GMT
addToFront, -05:00addAfter
addToRear, it.remove();
System.out.println(current);
current = current.next; }
if(n == 0) quadratic sort. O(n^2)nested loop- bubble sort – repeatively exchange adjaclent
return 0; elements if not in order, bubbles to the top having highest value
• The first line obtains the iterator, then the loop uses hasNext and next to access and print each else Log sort. O(logn) divide elements in half recursively, O(n) partition at each level,
book return n + sum(n-1); O(nlogn) total but could be O(n^2) if bad partition is chosen. quick sort – pick
} element, put other elements left or right of this element, recursively do the same to
Iterator: recursive definition of K(n), which represents the product of all of the even integers less than or both sides (partitions) Quick sort works by first selecting a pivot. The list is then
- no ADD method equal to n. divided into two sublists containing elements that are smaller than the pivot, and
elements that are bigger than the pivot, with the pivot in the middle of these two
K (1)=0 lists. Then quick sort is recursively called on the two sublists. The base case of the
recursion is a list with a single element, which is already considered sorted.
An inner class is a class that is declared inside of another class. A list iterator class is only for the
use of the class that implements the list, and as such is private to the list class. The list class
K (2)=2 Log sort. Divide list in half repeatedly for O(logn), merging is O(n), total is O(nlogn).
merge sort – divide in half repeatedly until 1 element, recombine.
should be iterable, but the list iterator class is not. The list iterator implements the Iterator Radix sort:
interface, but it is a concrete class and not itself an interface In a radix sort, the radix is the number of queues, which is the number of possible values of each
K (n)=n∗K ( n−2)if nis even∧greater than2 digit or character in a sort key.
A user-defined iterator needs to know the size of the collection when the iterator is created. The
iterator uses this to detect if the collection is modified via a reference to the collection. If
modifications are detected, the iterator throws a ConcurrentModificationException.
K (n)=K (n−1) if n isodd ∧greater than 2
The for-each loop can also be used instead of hasNext and next methods. It does not explicitly
declare an iterator, but Java translates the for-each code into code that uses an iterator before the method that computes the product of all of the even integers less than or equal to n.
code executes. public int productOfEvens(int n)
for (type var : array) {
{ if(n <= 1) Comparator objects are not part of the class whose objects are being compared, so the class does
statements using var; return 0; not need to extend or inherit anything other than what it already inherits or extends. Comparator
} if(n == 2) objects are separate from the class of objects being compared, but are used by the sort method of
is equivalent to: return 2; the Arrays class to determine the sort order.
for (int i=0; i<arr.length; i++) if(n%2 == 0)
{ return n*productOfEvens(n-2); The Comparator interface requires a body for the compare method. It is the Comparable interface
type var = arr[i]; else that requires a body for the compareTo method.
statements using var; return productOfEvens(n-1);
} } Trees:
Height / depth = longest path from root to a leaf
isPalindrome method: Tree classification:
Iterable: isPalindrome(String s) Order of tree = Max # of children any node can have
The for-each loop can be used on any object that is Iterable if the length of the string is 1 General trees = no limit to number of children, unlimited order
for (Book book : myList) return true N-ary: N order of tree, each node having N children limit is an N-ary tree
System.out.println(book); else if the length of the string is 2 and the two characters are the Binary tree = max Order of 2
same Balanced tree = all leaves at same level or one level of each other. N-ary tree height with m
return true elements is lognM. binary tree with n nodes has height log2n
else if the first and the last characters are the same Full tree = N-ary tree is full if all leaves are at same height and every non-leaf node has n children
return isPalindrome(the string created by removing Complete tree = full OR full to the next to last level with all leaves at the bottom level on the left
Recursion the first and last characters) side of the tree
else Array trees (for complete binary trees):
return false - Computed child links = left child is 2n+1, right child is 2*(n+1). if not complete this
waste lots of array space
A method invoking itself is considered to be direct recursion - Simulated Child links = Each element of the array is an object that stores a
A method could invoke another method, which invokes another, etc., until reference to the tree element and the array index of each child. first come first
eventually the original method is invoked again. This is called indirect recursion serve, modeled after computer memory
Searching/Sorting: Tree traversals:
Recall that the compareTo method returns an integer that specifies the relationship between two - Preorder: root, left, right visit the root, then traverse the subtrees from left to right
recursive definition of the sum of the first n integers, S(n) objects: - Inorder: left, root, right traverse the left subtree, then visit the root, then traverse
obj1.compareTo(obj2) the right subtree
S(0) = 0 This call returns a number less than, equal to, or greater than 0 if obj1 is less than, equal to, or - Postorder: left, right, root traverse the subtrees from left to right, then visit the
S(n) = n + S(n – 1) for n > 0 greater than obj2, respectively root
recursive method that computes the sum of the first n integers: - Level-order (breath first): It is implemented iteratively using a queue.visit each
public void selectionSort(int [] array) node at each level of the tree from top (root) to bottom and left to right
public int sum(int n) {
{ int minIndex, temp;
for(int i = 0; i < array.length; i++)
{
Comparable Comparator – no commit of class to
particular comparing technique
minIndex = i;
for(int j = i+1; j < array.length; j++) -
{ - involves a queue data structure. The main part of the algorithm dequeues a node
1) Comparable provides a single sorting sequence. In other The Comparator provides multiple sorting
if(array[j] < array[minIndex]) from the queue, enqueues its left and right child, and then visits the node. The first
words, we can sort the collection on the basis of a single sequences. In other words, we can sort the minIndex = j; step of the algorithm enqueues the root, and it continues until the queue is empty.
element such as id, name, and price. collection on the basis of multiple elements }//end for j - A
such as id, name, and price etc. temp = array[i]; - / \
array[i] = array[minIndex]; - B C
array[minIndex] = temp; - / \ \
2) Comparable affects the original class, i.e., the actual class is Comparator doesn't affect the original class,
modified. i.e., the actual class is not modified. }//end for i - D E F
} -
LEFT ROTATION -
3) Comparable provides compareTo() method to sort Comparator provides compare() method to Let the root node be denoted root, and denote its right child as right and its left child as left. First, - Postorder – D, E, B, F, C, A; Preorder – A, B, D, E, C, F; Inorder – D, B, E, A, C, F;
elements. sort elements. we make left the new root element. Next, we make root the right child element of left. Finally, we Level-order – A, B, C, D, E, F
make the former right child of left the left child of root. - Preorder Print
4) Comparable is present in java.lang package. A Comparator is present in Sorts – -
the java.util package. Sequential sort requires N^2 comparisons, Log sorts require Nlog2N - public void preorder(BinaryTreeNode root)
quadratic sort. O(n^2)nested loop- selection sort – find smallest value, switch it - {
with first pos, repeat - System.out.println(root.getElement());
5) We can sort the list elements of Comparable type We can sort the list elements of Comparator quadratic sort.
04-12-2023 O(n^2)nested loop- insertion sort – insert items 1 by 1 based on first
This study source was downloaded
by Collections.sort(List) method. by
type 100000780412656
by Collections.sort(List, from CourseHero.com on 15:46:06 GMT -05:00 - if(root.getLeftChild() != null)
Comparator) method.
item being a sorted list - preorder(root.getLeftChild());
- if(root.getRightChild() != null)
- preorder(root.getRightChild()); distinct. A map can be searched to determine if it contains a particular key or value,
- } and to retrieve the value associated with a particular key.
- Inorder Print Location is determined by some hashing function of element value, stored in hash table
- public void inorder(BinaryTreeNode root) o Each location = cell or bucket
- { o Chaining Method: Each cell is a collection (a list in this case) of elements, ordered or
- if(root.getLeftChild() != null) unordered
- inorder(root.getLeftChild()); Removing:
- System.out.println(root.getElement()); o 1) uniquely mapped: just remove the element
- if(root.getRightChild() != null) o 2) overflow index: replace element with next index value
- inorder(root.getRightChild()); Heaps o 3) end of list of elements: set to null, set the next pointer of prev element to null, and
- } - The addElement operation is O(log n). This is true in both a link implementation and in an add that pos to the overflow
o array implementation of a heap. o 4) middle of list: set its pos in the overflow to null, and est point of the prev element to
Expression tree - There is no rebalancing needed WHEN ADDING TO A HEAP skip it
- complete tree where each element less or equal to both children, structural (needs to be o 5) not in table: throw exemption
complete) and ordering constraints o Open Addressing Method: Looks for another unused position in the graph via:
- Add elements as leaf, exchange positions with parent until appropriate Linear Probing: Try (P+1)%S where S is the size of the table and P is the current
- Removing the root (min): last leaf is new root (far right leaf), then fix relationships (e.g. swap position. Problem: can create clusters of occupied cells.
element with child if its smaller) Quadratic probing: Same as above but replace 1 with 1^2, 2^2 etc to create spread and
reduce clustering
Double Hashing: hash again using the first hash key and table location
Functions
o Extraction = part of element key value is used to compute locations, like with alphabet
Linked binary tree: for names
- o Division: location is computed mathematically. Hashcode(key) = Math.abs(key) % p.
LinkedBinaryTree = reference to root node
Priority Queues for positive int P result will be 0 to p-1.
BinaryTreeNode = represents each Node, with links to left/right children if
Removes in order regardless of when added o Folding: key is divided into 2 parts and combined to create index. Divide key where
applicable
can be implemented using a list of queues, where each queue corresponds to a each part is same length as desired key.
BST:
particular priority. It can also be implemented using a minheap, where the compareTo o Shift Folding: parts are added to create index
- BST is a binary tree where for each node n the left subtree contains
method for each element is designed to compare priorities of elements first, then to o Boundary folding: some parts reversed before shift folding
elements < element stored in N and right >= the element stored in n
compare the order of the elements second if the priorities are the same. o Mid Square Method: key is multiplied by itself and then extraction method used from
- To find: compare target to node element, left if target is less, right if target t
is greater middle (however many digits)
Linked Heaps: need to move up and down, so parent pointer is needed in heapnode class, so
- Need to be able to determine relative ordering on data type, comparable o Radix Transformation: Key turned into another numeric base (e.g. 23 in base 10 is 32 in
we always know where last leaf is
interface provides this base 7), then use division method
Heap sort: sorts by adding each element to a heap then removing one at a time, ascending
- To add: follow path until no child found then add o Digit Analysis Method: Extract and manipulated specific digits from key. e.g. reverse,
order as smallest element comes off first Iinvolves adding each element to a heap, then
- Removing node situations: swap pairs
removing each element from the heap. Adding and removing are each O(log n)
o 1) leaf: just remove o Length Dependent Method: key and key length combined to form index or pre index.
operations, and there are n elements to be added and removed, so heap sort is O(n log
o 2) one child: deleted node replaced by child i.e. if key is 8765 multiple by 4 and then divided by the last digit
n).
o 3) 2 children: find appropriate node using inorder successor (child) or predecessor (ancestor). o A red/black binary search tree is used as the underlying data structure of a map or set
Children of removed node become replacement node children class
Graphs:
Nodes are called vertices instead, usually have label or name. no root node.
To get an integer key:
Edges are referred by the vertice labels they connect
o Object class has hashcode method that returns int based on memory location
Undirected: pairings represented by edges are unordered.
- Edge can be traversed in either directions. 2 vertices are Adjacent if edge connected o Sub classes sometimes make their own hashcode method, such as String and Integer
them. Also called neighbors. Java collections API hashing implementations (7):
- Selfloop/sling: edge connects a vertex to itself – Hashtable – legacy, retains key-value pairs (1, “bob”). neither can be null.
- Complete if max number of edges connect the vertices A complete graph is a graph in – HashMap - Same as hashtable but allows null and better performance
which every vertex is adjacent to every other vertex.. Connected if for any 2 vertices – HashSet – no duplicate values
there is a path between them; has n(n-1)/2 edges. – IdentityHashMap
o – LinkedHashMap
- Path = sequence of edges connecting 2 vertices
o Degenerate tree = unbalanced length is the number of edges aka # vertices - 1 – WeakHashMap
AVL trees (numeric balance factor checked – diff between heights of subtrees RIGHT MINUS Cycle = path where first and last vertices are the same with no repeated edges. Acyclic means
LEFT) and red/black trees (children of red nodes are black, every path from root needs same a graph with no cycles
num of black nodes) ensure balancing Directed graph (aka digraph): edges are ordered pairs of vertices. So the edges A,B and B,A are
rotations are operations to assist with keeping balance separate, directional edges
o Right rotation: Path is now a sequence of directed edges connecting 2 vertices
Weighted graph aka network: Weights/costs associated with each edge. Path weight is the
sum of edge weights. Each edge has the labeling AND a weight now (3 values)
Traversal:
Breadth first = like level-order. Can make using queue (for traversing) and iterator (for result).
o Left rotation: - enqueue the starting vertex, and mark it as “visited”. loop until queue is empty
• dequeue first vertex and add it to iterator
• enqueue each unmarked vertex adjacent to the dequeued vertex
• mark each vertex enqueued as “visited”
Depth first = like preorder. Same as above but use stack. and do not mark vertex as visited until
it has been added to the iterator.
Overall connected graph = size of breadth first traversal at any vertex is N (the # of vertices)
Spanning tree = all vertices but some possibly not all edges
o right/left rotation: MST = sum of the weights of edges is least possible. Use minheap.
o simplest approach – a variation of the breadth-first traversal algorithm look for the
cheapest path in a weighted graph
o use a minheap or a priority queue storing vertex, weight pairs
Implementing graphs:
• Adjacency lists –
o use a set of graph nodes which contain a linked list storing the edges within each node
o for weighted graphs, each edge would be stored as a triple including the weight
Hashing:
: A set is a collection in which the objects are distinct. It can be efficiently searched to
o left/right rotation: determine if the set contains a particular object. A map contains objects that have keys –
This study source was downloaded by 100000780412656 from CourseHero.com on 04-12-2023
and values. All 15:46:06
of the keys inGMT -05:00
a map must be distinct, but the values may not be
–
This study source was downloaded by 100000780412656 from CourseHero.com on 04-12-2023 15:46:06 GMT -05:00
Powered by TCPDF (www.tcpdf.org)