CSS 143 Final Exam
Trees: Big O Motivation {Insert, Find}
1) Binary Search Trees are quick -insert and find 2) O(insertInOrderedArray) = O(n) 3) O(insertInSearchTree) = O(log n) 4) O(linearSearchUnorderedArray) = O(n) 5) O(binarySearchOrderedArray) = O(log n) 6) O(binarySearchInSearchTree) = O(log n)
Big O does not address...
1) Changes that are hardware-dependent 2) Memory requirements (Spacial complexity) 3) Disk or network requirements
Determining Big O
1) Count steps, create formula 2) Find reference or bounding function 3) Find simpler limiting function as n -> infinity
General step wise procedure for Big O runtime analysis
1) Figure out what the input is and what n represents 2) Express the maximum number of operations, the algorithm performs in terms of n 3) Eliminate all excluding the highest order terms 4) Remove all the constant factors
Processing Order
1) Inorder -Process left subtree -Process data in root -Process right subtree 2) Preorder -Process data in root -Process left subtree -Process right subtree 3) Postorder -Process left subtree -Process right subtree -Process data in root
What algorithms use Big O?
1) List Operations -Insert/Delete -Find 2) Searching Problems -Linear or sequential search -Binary Search 3) Sorting (and merging) -Bubble Sort -QuickSort 4) Series, Sums, Exponentiation -Factorial -Fibonacci Numbers
HashSet
1) Lists -elements can occur more than once -elements are indexed -ordered -get, remove, add use position index 2) Sets -no duplicates -for add, does nothing if element is in list An array of buckets for storing data. A has functions determines which bucket the data will be put into. If more than one element ends up in a bucket (a collision), then a linked list stores all the elements in the bucket. A good hash distributes elements evenly. Best case is O(1)
Pitfalls with generics
1) The can not hold primitives ArrayList<double> list //wont compile 2) No building objects of type T -T variable = new T(); //fail 3) No arrays of -T[] a = new T[10]; //also fails
Preconditions of Big O
1) We know an algorithm is an ordered set of steps(a program). 2) We seek to break up our (possibly large) program into discrete, known pieces. 3) Consider each piece in turn, divide and conquer strategy to analysis.
Binary Trees
A binary tree is a recursive data structure where each node can have 2 children at most. A common type of binary tree is a binary search tree, in which every node has a value that is greater than or equal to the node values in the left sub-tree, and less than or equal to the node values in the right sub-tree.
try-catch block
A block for handling exceptions - one that tries to run code and another that handles the exception.
Basecase
A branch in a recursive function that does not make a recursive call.
Privacy Leak
A class definition where an instance (or class/static) variable meant to be private is exposed to being read or changed by a scope of the program outside of said class.
Big O Notation
A classification system. A way of expressing the worst-case run-time of an algorithm, useful for comparing the speed of two algorithms. It typically describes execution speed but can also describe memory requirements and average case runtime rather than worst case runtime.
Sets
A collection of unique values (no duplicates allowed) that can perform the following operations efficiently: -add, remove, search (contains) -we don't think of a set as having indexes, we just add things to the set in general and don't worry about order (Array, Linked List, Tree)
Collisions
A collision, or more specifically, a hash code collision in a HashMap, is a situation where two or more key objects produce the same final hash value and hence point to the same bucket location or array index. HashMap handles collision by using a linked list to store map entries ended up in same array location or bucket location.
"has a" relationship
A connection between two objects where one has a field that refers to the other. The contained object acts as part of the containing object's state. This is like when a class has another class.
Copy constructor
A constructor that takes in an object of some class and uses that object's information to create a new object of the same class.
"is" relationship
A hierarchical connection between two categories in which one type is a specialized version of the other. This is how the relationship of the subclass and superclass works. As a derived class, you are a member of the parent class.
super
A keyword used inside the derived class to call the parent class's (public) methods and variables.
Linked List
A linear data structure that works as a collection of nodes. Each item is stored in a node, and each node has both the data it's meant to store and a link to the next node.
Singly Linked List
A linked list that can move down the list in one direction only.
Doubly Linked List
A linked list that has one link with a reference to the next node and one with a reference to the previous node.
Recursion
A method is said to utilize this if:- It (sometimes) calls itself.- It has a basecase when it doesn't call itself.- Each time it calls itself, the problem gets closer to being solved. (Otherwise, you will get an infinte loop.)
Trees
A non-linear data structure where data objects are organized in terms of hierarchical relationship. The structure is non-linear in the sense that, unlike simple array and linked list implementation, data in a tree is not organized linearly. Each data element is stored in a structure called a node.
Sort Preconditions
A set of items can only be sorted if there exists some well-ordering or total ordering on all the elements of that set.
Insertion Sort
A simple sorting algorithm that builds the final sorted array (or list) one item at time. It is much less efficient on large lists than more advanced algorithms such as quicksort, heapsort, or merge sort. Big-O = O(n^2).
QuickSort
A sort in which a list is first partitioned into lower and upper sublists for which all keys are, respectively, less than some pivot key or greater than the pivot key. Big-O = O(n^2).
Bubble Sort
A sort in which the first two items to be sorted are examined and exchanged if necessary to place them in the specified order; the second item is then compared with the third (exchanging them if required), the third is compared with the fourth, and the process is repeated until all pairs have been examined and all items are in the proper sequence. Big-O = O(n^2).
Merge Sort
A sort that splits the list into two equal halves and places them in separate arrays, each array is recursively sorted then merged back together to form the final sorted list. Big-O = O(n log n)
A class invariant describes
A state or condition that is true for all objects of the class.
Ways that a privacy leak can occur
- Defining the variable and/or method using "public" rather than "private."- Setting the return value to a class-type variable, and then return a reference to that variable's content's memory location.
A copy constructor
Accepts one input parameter.
Operations (steps) on a CPU
Algebraic {+ , -, ++, --, *, /} Relational {==, !=, <, >, <=, >=} Logical {&, &&, |, ||, !} Assignment and array access {=, []}
How to fix privacy leaks
Change "public" to "private" and call a constructor to make new copies.
Overriding
Creating a method in the derived class with the same name and signature as the superclass, which replaces the superclass's version in the derived class. The superclass can still be called using super.
Overloading
Creating multiple methods of the same name, but with different parameters, in the same class.
Hash Tables
Data structure used to implement an associative array. Maps keys to values. An associative array, map, symbol table, or dictionary is an abstract data type composed of a collection of (key, value) pairs, such that each possible key appears at most once in the collection. Uses hash function to compute an index into an array. Array entries hold buckets or slots. Can find value in bucket.
Abstract data types
Describe data structures independent of implementation details.
When overloading a constructor, each constructor version must have
Different signatures.
Descendant Classes
Subclasses over one generation apart.
Ancestor Classes
Superclasses over one generation apart.
Object
The "original" Java class, the ancestor class of every class in Java. Every class you create is implicitly just a replication of it.
Why compare algorithms?
We have problems and algorithms solve these problems, but not all are "==". Some are quick (time) or small (space). Some are easy to implement and some are particularly clever. Some are bad (large, slow, or both).
Are exceptions objects?
Yes. They are objects. The "e" object usually defined in the textbook is just an object representation of one - it has a dot after it, and having dots after variables is a way to signify objects.
Consider an object myObj. Given that a legitimate line of code using this object is: int a = myObj.doThis(4.0); which of the following possible headings for doThis is consistent with the above call? a) public int doThis(double input) b) private int doThis(double input) c) public void doThis(int input) d) public double doThis(int input)
a)
The correct code to remove and print the elements of a stack of Integers is a) while (!stack.isEmpty()) { System.out.println(stack.pop()); } b) while (stack.size() > 0) { System.out.println(stack.pop()); } c) int n = stack.pop(); while (n != null) { System.out.println(n); n = stack.pop(); }
a)
Which code snippet below best exemplifies how to define an accessor method (and any related quantity/ies) in a class definition? a) private int data; public int getData() { return this.data; } b) public int data; public int getData() { return this.data; } c) private int data; public static int getData() { return this.data; } d) private int data; public void getData() { return this.data; } e) private int data; private int getData() { return this.data; }
a)
private boolean checkThis(Integer num1, int num2, double num3) which of the following is the method signature? a) checkThis(Integer, int, double) b) boolean checkThis(Integer, int, double) c) checkThis(int, int, double) d) The method has no signature because the method is private. e) checkThis(boolean, Integer, int, double)
a)
Consider class Foo with the following definitions: public class Foo { public int a; private int b; protected int c; public void doThis() { [... method code here ...] } } which of the following are NOT directly available (i.e., available by name) to a child class of Foo? You can assume the child class is in the same package as Foo. a) All instance variables and methods defined in Foo as given above are directly available. b) b c) c d) a e) doThis
b)
Given a class and the method public class ABC{int a = 10;}public void doSomething(ABC abc) { abc.a = 3; } The ouput of the following is ABC abc = new ABC(); doSomething(abc); System.out.println(abc.a); a) 13 b) 3 c) 10
b)
If a program defined enum Trees { OAK, WILLOW, PINE, ASPEN, DOGWOOD}; int[] heights = { 51, 25, 30, 65, 34, 12}; What is the output from: System.out.println(heights[Trees.ASPEN.ordinal()]); a) ASPEN b) 65 c) 30 d) Trees.ASPEN
b)
The following is the header for a method that expects only the input "yes" and uses an assert to check for this. public static void onlyYes(String s) The method is called with onlyYes("no"); Which of the following lines of code in the method would produce the output: Exception in thread "main" java.lang.AssertionError: no a) assert s.equals("yes"): s; b) assert (s.equals("yes")) c) assert("no"); d) assert(true);
b)
Which is a correct usage of the static class Math? a) Math math = new Math(); int r = math.round(4.3); b) int r = Math.floor(4.3); c) int r = math.pow(4, 2);
b)
Which of the following defines a no-argument constructor for the class OurClass? a) public void OurClass() b) public OurClass() c) public OurClass(OurClass noarg) d) private void OurClass()
b)
Given a method public void doSomething(int a) { a = 3; } The output of the following is int b = 10; doSomething(b); System.out.println(b); a) 13 b) 3 c) 10
c)
If a 2-dimensional array int[][] array is created to have 3 rows and 4 columns, then array.length is a) 4 b) 12 c) 3
c)
Which of the following method definitions is recursive? a) public int doThis(int input) { if (input > 0) { return 0; } else { for (int i = input; i < 0; i++) { System.out.println("hello"); } } } b) public int doThis(int input) { if (input > 0) { return -1; } else { return doElse(input++); } } c) public int doThis(int input) { if (input > 0) { return 0; } else { System.out.println("hello"); return doThis(input++); } } d) public int doThis(int input) { if (input > 0) { return 0; } else { return doElse(input++); } }
c)
Which of the following operations are part of the "stack" abstract data type? a) dequeue b) insert at index c) push d) get by index e) enqueue
c)
Consider the following definition of a method in a class: public void doThis(int x, double y) Which of the following is a legitimate case of overloading doThis in the class definition? a) private void doThis(int x, double y) b) public int doThis(int a, double b) c) private void doThis(int a, double b) d) public void doThis(int x, int y)
d)
Which of the following operations are part of the "list" abstract data type? a) push b) enqueue c) pop d) add or append
d)
Which of the following would be a reason to use an ArrayList instead of an array? a) You want to be able to access the data elements as fast as possible. b) You do not want to randomly access any element of data in the structure. c) You only want to access the first element of the structure. d) The number of elements in your collection of data is unknown and variable.
d)
Mutator methods are designed to
Alter private instance variables.
Exceptions
An error or other message raised by the interpreter or compiler to indicate a special circumstance that should be handled. If it is not handled, the program will stop and report the error.
Stack Overflow
An error that occurs if you call a recursive method that will never get to its basecase, as the computer will be out of memory to allocate variables and arguments.
Interfaces
An interface is a declaration of empty methods and can be thought of as a fully abstract class. Like a class with no implementation.
O(log n)
Any algorithm which cuts the problem in half each time. O(log n) operations run in logarithmic time - the operation will take longer as the input size increases, but once the input gets fairly large it won't change enough to worry about. An example of an O(log n) operation is finding an item in sorted list with a balanced search tree or a binary search.
In "information hiding," the "information" being hidden
Are the details of implementation.
Generics
Extend Java's type system to allow "a type or method to operate on objects of various types while providing compile-time type safety". Require a type variable which traditionally <T>.
O(n^2)
For every element, you do something with every other element, such as comparing them. O(n^2) runs in quadratic time - the operation is only really practical up to a certain input size. Every time n doubles, the operation takes four times as long. Examples of this are quicksort (in worst case) and bubble sort. Stepping through a multi-dimensional array.
A class without an explicit (written) constructor
Has a no-argument constructor automatically provided.
Void methods
Have no return value.
Inheritance vs. Implementation
In Java, you can implement more than one interface, but you cannot inherit from more than one subclass. This is the opposite of what most programming languages have.
Characteristics of an algorithm
Input: Input values from a specified set. Output: From each set of input values, an algorithm produces output values from a specified set. The output values are a solution. Effectiveness: It must be possible to perform each step of an algorithm exactly and in a finite amount of time. Generality: The procedure should be applicable for all problems of the desired form, and not just for a particular set of input. Definiteness: The steps of an algorithm must be precisely defined. Correctness: An algorithm should produce the correct output values for each set of input values. Finiteness: An algorithm should produce the desired output after a finite (but perhaps large) number of steps for any input in the set.
The following is an example of unboxing:
Integer inum = new Integer(5); int num = inum;
Interfaces vs Abstract
Interfaces and abstract classes are both used for abstraction. Interface can have only abstract methods. An abstract class can have abstract and non-abstract methods. Variables declared in a Java interface are by default final. An abstract class may contain non-final variables. Abstract class can have final, non-final, static and non-static variables. The interface has only static and final variables. Abstract class can provide the implementation of the interface. Interface can't provide the implementation of an abstract class. A Java interface can be implemented using the keyword "implements" and an abstract class can be extended using the keyword "extends". Interface supports multiple inheritance; an abstract class does not support multiple inheritance. Members of a Java interface are public by default. A Java abstract class can have class members like private, protected, etc.
O(n^!)
Involves doing something for all possible permutations of the n elements. O(n!) operations run in factorial time - the operation is impractical for a reasonably large input size n. An example of an )(n!) operation is the traveling salesman problem. Given a list of cities and the distances between each pair of cities, what is the shortest possible route that visits each city exactly once and returns? Heavily studied for optimization.
Iterable Interface
It means an object can be iterated, or stepped through. Two levels of classes are needed: the iterable object and its iterator. The object implements the iterable interface: -returns an iterator -an iterator has two methods that allow you to step through object hasNext() and next()
Serializable Interface
Java assigns a serial number to each object. If written more than once, only serial number written and makes file I/O more efficient. Instance variables in class must also be serializable. For security, bot all classes are serializable. Use transient qualifier to indicate a field should not be serialized. Why Use it? To save/persist state of an object To travel an object across a network
extends
Keyword in the class heading that creates the inheritance relationship.
Base cases
Stop a recursive stack.
Queue
Lists (ADTs) considered "FIFO" (first in/first out) because you add items to the back (enqueue) and remove items from the front (dequeue).
Stack
Lists (ADTs) considered "LIFO" (last in/first out) because you can add items to the top (push), remove the top (pop), and return the top without removing (peek).
O(1)
Means that no matter how large the input is, the time taken doesn't change. O(1) operations run in constant time. Some examples: Determining if a number is even or odd. Using a constant-size lookup table or has table.
O(n)
O(n) means that for every element, you are doing a constant number of operations, such as operations, such as comparing each element to a known value. O(n) operations run in linear time - the larger the input, the longer it takes, in an even tradeoff. Every time you double n, the operation will take twice as long. An example of this is finding an item in an unsorted list.
The "queue" abstract data type
Operates on the "first in, first out" principle.
O(n log n)
Performing an O(log n) operation for each item in your input. Most (efficient) sort algorithms are an example of this. O(n log n) operations run in loglinear time - increasing the input size hurts, but may still be manageable. Every time you double n, you spend twice as much time plus a little more.
Stable Sort
Preserves the order of duplicates in a sorted list.
Comparable Interface
Similar in spirits to equals, but more advanced. Used to compare an object of the same class with an instance of that class, it provides ordering of data for objects of the user-defined class. @Override public int compareTo(Object o) a.compareTo(b) return -1 (if a < b) return 1 (if a > b) return 0 (a == b)
Superclass
The base class a subclass inherits from. Also called a parent class.
Rules of Inheritance
The derived class do the following: - It can add new methods and instance variables. - It can override or overload the methods inherited from the base class. - It inherits everything that is public.
Addition Theorem: Sum of Functions
The larger of the two worst-case complexities dominates when summing.
Product of Functions Theorem
The product of two functions has the worst-case complexity equals to the product of the two individual worst-case time complexities. (nested loops)
Subclass
The specialized class that inherits the superclass. Also called a derived or child class.
Inheritance
The subclass (child class) inherits the public methods and public instance variables of the superclass (parent class).
Common Classes of Complexities
o(1) constant complexity o(log n) logarithmic complexity (sub-linear) o(n) linear complexity o(n log n) "n log n" complexity (nearly linear) o(n^b) polynomial complexity O(b^n), where b > 1 exponential or geometric complexity o(n!) factorial complexity o(n^n)
If I want to be sure my variable is never changed inside or outside of my class, I could declare it
public static final MINUTES_PER_HOUR = 60;
