Exam 1 Ozbirn

Pataasin ang iyong marka sa homework at exams ngayon gamit ang Quizwiz!

interface

- group of related methods with empty bodies - always abstract

exceptions

- thrown when precondition fails - checked exception - checked at compile time, must be handled by a try-catch block or the method declaration - unchecked exception - not checked at compile time - inherited from RuntimeException

What is the purpose of data structures? (3)

1) Real-world data storage 2) Programmer tools 3) Real world modeling

What are the disadvantages of a queue? (1)

1) Slow access to other items

What are the disadvantages of a stack? (1)

1) Slow access to other items

What are some preconditions that can be used for queues?

1) To insert, queue must not be full 2) To remove, queue must not be empty 3) to peekFront - queue must not be empty 4) to avoid runtime error, queue user must check first using isEmpty and isFull

What are pre-conditions to check for a stack? (5)

1) To push, the stack cannot be full 2) is the stack static or dynamic? 3) To pop, the stack must not be empty 4) To peek, the stack must not be empty 5) To avoid runtime error, stack user must check first using isEmpty or isFull

What is the step by step process of figuring out the cost of recursion or Big Oh?

1) find relationship between C and T; as long as n> or = 1 2) Take away the negative terms (bc it makes the equation bigger) 3) Multiply the the terms together 4) Add the constants together and you get the term n^3

Give a 5 elements stack S (from top to bottom: 2, 4,6,8,10 ) and an empty queue Q. Remove the elements one by one from the stack S then insert them into queue Q; then remove them one by one from queue Q and re-insert to the stack S.Now S looks like (from top to bottom):

10, 8, 6, 4, 2

Our last return would've been the ________________________ see slide 39

11, the 13 or the 20

Recall that the linear list access function: AN = A0 + N * w that is used to calculate the location of an element of the array from its node numberwhere Ao is the byte address of the first node called the base addressw is the node width (number of bytes per node) andN is node number, starting from 0Apply this function to calculate the memory address of the node stored at index 4 where base address = 100, node width = 10

140

Suppose it took 10 seconds to sort a list of N items using merge sort (where N is a large number). Recall that merge sort is an O(N log N) algorithm. Which of the following would be the most likely timing for merge sorting a list of 2N items?

22 seconds

for the following code what is the output: public static int power(int x, int n) { if (n = = 0) return 1; else return x * power(x, n-1); } power(5, 2)

25, = 5*(5 * power(5, 1)) =5*(5 * ( 5 * power(5, 0)

X^n + X^n

2X^n

I am going to execute this code with THREE pushes and ONE pop: stack <int> s; s.push(1); s.push(2); s.push(3); System.out.println(s.pop( )); What is the output?

3

How many basic rules are for when writing recursive routines

4 basic rules

Suppose it took 10 seconds to sort a list of N items using selection sort (where N is a large number). Recall that selection sort is an O(N2) algorithm. Which of the following would be the most likely timing for selection sorting a list of 2N items?

40 seconds

What does the following code print if 6371 is passed in as n? public static void print(int n) { if (n >= 10) print( n / 10); printDigit( n % 10); }

6 ( printDigit(6%10); ) 3 ( printDigit(63%10); ) 7 ( printDigit(637%10); ) 1 ( printDigit(6371%10); )

They are the operations that perform on the Queue structures Enqueue, Dequeue int[ ] values = { 1, 3, 5, 7, 9, 11, 13, 15, 17, 19 }; Stack s = new Stack(10); for (int i = 0; i < 10; i ++) s.push(values[ i ]); int sum = 10;for (int n = 0; n <3; n++) sum = sum + s.pop(); System.out.println (sum); What is the output?

61

what is the base case? public static void print(int n) { if (n >= 10) print( n / 10); printDigit( n % 10); }

9 or less

∑i=0→N-1 (c^i)

= (cⁿ-1)/c-1

∑i=0→N (2^i)

= 2ⁿ⁺¹-1

∑i=1→N (i^2)

= N(N+1)(2N+1)/6

∑i=1→N (i)

= N(N+1)/2

sum=0; for (i=1;i<n;i++) for (j=1;j<i*i;j++) if (j%i == 0) for (k=0;k<j;k++) sum++;

?

What is an algorithm?

A formalized plan to accomplish some task.

What is a doubly linked list?

A linked list that has pointers to the next node and the previous node

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 polymorphism?

polymorphism applies to classes in an inheritance hierarchy can pass a derived class wherever the parent class is expected the appropriate method for the class is called

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.

What is the reason for using a "circular queue" instead of a regular one?

reuse empty spaces

recursion

running time for ____ is O(N) because each call generate one more recursive call up to 'N' times similar to a for-loop

linear search

running time of O(N)

binary search

running time of O(log(N))

exponentiation

running time of O(log(N))

JUnit

runs rests independently

How to search a list?

sequential search traverses the list from beginning to end check each entry in the list if matches the desired entry, then FOUND (return its index) if traverse entire list and no match, then NOT FOUND (return -1) recall: the ArrayList class has indexOf, contains methods

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

abstract data type

set of objects with a set of operations which is a mathematical abstraction; operations are defined but NOT the implementation of operations can be lists, sets, and graphs

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

linked list

uses a series of nodes where each nodes contains a pointer to the next node

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

type erasure

when generic classes are seen by the compiler but are still converted to regular classes during compilation

Proof by Counterexample is __________

where you simply show a case where it isn't true

log(n)

with this running time, the function gets smaller

We look at _______ case, mostly

worst

upper bound

worst case, most amount of work performed

Priority Queue

A priority queue has a highest priority, first out protocol

java generics

- allow types to be parameters

What does a single linked lists consist of?

-has a front and a back -great for stacks and queues -each node has a data value and an address

What are the advantages of a linked list? (2)

1) Quick insertion 2) Quick deletion

What are the advantages of an unordered array? (2)

1) Quick insertion 2) Very fast access if index known

What are some issues with lists? (3)

1) Slow insert and delete 2) Static size limit 3) Can't make array dynamic w/o vectors

What are the disadvantages of an ordered array? (2)

1) Slow insertion and deletion 2) Fixed size

What are the disadvantages of a linked list? (1)

1) Slow search

What are the disadvantages of an unordered array? (3)

1) Slow search 2) slow deletion 3) Fixed size

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

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

2^n + 2^n

2^(n+1)

Three criteria are used to determine whether a data structure is acceptable for a particular application are: A. Cost, Speed, and memory overhead B. Cost, type of storage, type of memory C. a and b D. None of above

A. Cost, Speed, and memory overhead

The Binary Search algorithm speed at the worst case is? A. O(log2n) B. O(n log2n) C. O(n) D. O(n2)

A. O(log2n)

Which of the following access modes cannot be used to access restricted structures? A. Update B. Fetch C. Insert D. None

A. Update

Unsorted array is array-based structure that ____ (page 66) A. is accessed in the key field mode B. uses an array of objects to store the data set C. the size is equal to the max number in the structure D. All of above are correct

All of above are correct

What is a field?

An atomic unit of information. In Java, a data member or field.

They are the operations that perform on the Queue structures A. Pop, push B. Enqueue, Dequeue C. Insert, Delete, Fetch, Update D. Add, Remove, get, set

B. Enqueue, Dequeue

The programmer-defined array structures support the following operations A. Fetch, Insert B. Fetch, Insert, Delete, Update C. Fetch, Update D. Fetch, Delete

B. Fetch, Insert, Delete, Update

Procedural abstraction is: A. We do not need to know what the method is to use it B. We do not need to know the implementation details of the method in order to use it C. We do not need to know what methods the class has to use it D. We do not to know anything about the method to use it

B. We do not need to know the implementation details of the method in order to use it

What log base do we use in data structures?

Base 2

Which one is not correct for the speeds of Unsorted-Optimized Array Structure operations?

C. Fetch: O(log2n)

The speed of Dequeue operation of Queue structure is: A. O(n) B. O(nlog2n) C. O(1) D. O(n2)

C. O(1)

The speed of Pop operation of Stack structure is:

C. O(1)

Data Structure is ____ A. An organization of information usually in the memory B. For better algorithm efficiency and improves the program's performance C. a and b D. none of above

C. a and b

Which one is correct about array? A. int [ ] myInt = new int; B. int [3] myInt = new int; C. int [ ] myInt = new int[3]; D. int [ ] myInt = new int(3);

C. int [ ] myInt = new int[3];

The operation for removing an entry from a stack is traditionally called: A. delete B. peek C. pop D. remove

C. pop

Which one is the programmer-defined array structure? (page 66)

D. All of above

How does insertion sort work?

Each element, one at a time, is added to a sorted (sub)array, which implies that elements are shifted to make room

stacks/dequeues

List implementation: - every operation is O(1) Array implementation: - amortized O(1) - due to array expansion - use % to stay in bounds and do wrap arounds

Bubble Sort Best case

O(N)

f(n) = n

O(n)

Lower bound (possibly equal).

Omega

What kind of queue permits cutting in line?

Priority queue

What does the Iterable interface provide?

The iterable interface provides an iterator which you can use to loop through a collection of objects.

X^a*X^b =

X^(a+b)

Which was the first base case we encountered? see slide 39

all the way left side -2, the last one on the right side -2

comparator

allows comparison rule to be separate from the object where it can be defined and passed into arguments (i.e.: public static <AnyType> AnyType findMax( AnyType [ ] arr, Comparator<? super AnyType> cmp ))

raw

instance of and typecasts only work with ____ types

map

map maintains a collection of key-value pairs

There be ___ class for all generic invocations.

one

C++ Containers

provides 16 container classes implementing ADTs with various data structures

The operation for adding an entry to a stack is traditionally called:

push

instanceof and typecasts work only with ___________

raw types

Inner classes

- non-static - have access to instance variables - ex: iterator

Implementation of an API? (4 stages)

1) ADT 2) API 3) App 4) End user

What are some properties of lists? (3)

1) Allows insertion or deletion anywhere 2) Slow insertion 3) Maintains data order

What are the advantages of a queue? (1)

1) Provides first in, first out access.

What are the four basic principles of recursion?

1. Always have a base case. 2. Make progress towards that base case. 3. Assume the recursive function works. 4. Do not duplicate computations unnecessarily.

matrix

2D array [row][column]

What does log base 2 of 3^4 equal?

4 * log base 2 of 3

In Java, a class is

A blueprint for one or more objects

What is a Data Structure?

A particular way of organizing data in a computer so that it can be used efficiently

What is recursion?

A programming technique that causes a method to call itself in order to compute a result.

Two objects, objectA and object, are objects of one class. The objectA is copied to objectB. How many objects exist after the copy if the copy is performed as a shallow copy? A. 1 B. 2 C. cannot know D. 1 or 2 depending on real cases

A. 1

The basic operations performed on data structures: A. Insert, delete, fetch, update B. Insert, search, delete, update C. Remove, search, insert, update D. fetch, modify, delete, read

A. Insert, delete, fetch, update

Tell what of the following does the acronyms LIFO describes for: A. Stack B. Queue C. Hashtable D. none of above

A. Stack

The Insert algorithm of Sorted Array Structure has the following steps, put the following steps in correct order (page 76) Step A: Using Binary Search Algorithm to search until finding two adjacent keys that backed the new node's key Step B: Move all the nodes below these two nodes and the larger of the two braked nodes down one element to open up a spot for the new node Step C: The content of the node that we want to insert is deep copied to the spot for the new created node then a reference to that node is placed in the array element that has been opened up

ABC

The process of separating how an operation is performed inside a class, as opposed to what's visible to the class user is called

Abstraction

What's the worst-case complexity of bubble sort? Selection sort? Insertion sort?

All O(N^2) --interpolation is O(N)

Which one is the programmer-defined array structure? (page 66) A. The Unsorted array B. The Sorted array C. The Unsorted-Optimized Array D. All of above

All of above

What is the efficiency of inserting and indexing an LinkedList?

An array list has an insertion time of O(1) but an index time of O(n)

What is the efficiency of inserting and indexing an ArrayList?

An array list has an insertion time of O(n) but an index time of O(1)

What is an 'online' algorithm?

An online algorithm is an algorithm that you can stop at any point in it's execution and it will give you the correct result up until the point you stop it. Best and most efficient type of algorithm.

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

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)

The initialized state of Unsorted Array structure n elements named data, which one is NOT correct: (page 66)

B. next is set to n-1

Two objects, objectA and objectB, are objects of one class. The objectA is copied to objectB. How many objects exist after the copy if the copy is performed as a deep copy?(PAGE 41) A. 1 B. 2 C. cannot know D. 1 or 2 depending on real cases

B. 2

They are the operations that perform on the Stack structures A. Enqueue, Dequeue B. Pop, push C. Insert, Delete, Fetch and Update D. Add, Remove, get, set

B. Pop, push

Built-in data structures are ____? A. Schemes for storing data that are conceived and implemented by the programmer of a particular program B. schemes for storing data that are part of a programming language C. constructed from structures, such as, parallel arrays, class definitions, hashing schemes, link lists, trees, stacks and queues. D. None of above

B. schemes for storing data that are part of a programming language

Fetch algorithm of Unsorted -Optimized Array Structure with the key targetKey has the following steps, put them in correct order (page 69-70 and 80) Step A: return a deep copy of it Step B: Use Sequential Search Algorithm starting at element 0 and down the array until an object with the given key is found Step C: Move the node reference up one index in the array unless the node being fetched is reference by element at zero

BCA

The Delete algorithm of Sorted Array Structure has the following steps, put them in correct order (page 74) Step A: next = next-1 and assign data[next] to null (reclaim unused storage) Step B:Use Binary Search algorithm to locate the node i to be deleted Step C: Move all the references below node i to node next-2 up one index

BCA

The Delete algorithm of Unsorted Array Structure has the following steps, put them in correct order (page 67) Step A: Set the array element that stores the reference to the node to null Step B:Use sequential search to locate the node to be deleted, the search begins at element zero and terminates when the node with the given key is located. Step C: Move all the node references below the deleted node up one element in the array and then decrement the memory cell next

BCA

What are the four basic rules when writing recursive routines (in summary)?

Base case, making progress towards the base case, assume recursive calls work without tracing it all out, don't duplicate work already performed in a previous call.

What is the first basic rule of recursion

Basic case: which can be solved without recursion

What property allows you to make an array like this: Person[] people = new Student[];

Because Student is a subclass of Person and because arrays are covariant, this assignment is acceptable. Only students can go in this array.

complexity breakdown

Best case, average, and worse case.

Upper bound (possibly equal).

Big O

Which sort is considered one of the worst sorts possible?

Bubble sort

The factors that determine the cost of software? A. Lines of code that the software contains B. Design, implement, testing, documentation, burdened labor rate C. A and B D. None of these are correct

C. A and B

Fetch algorithm of Unsorted Array Structure with the key targetKey has the following steps, put them in correct order (page 69-70) Step A: return a deep copy of it Step B: Use Sequential Search Algorithm starting at element 0 and down the ar ray until an object with the given key is found (page 71) A. AB B. AB and need one more step C. BA D. BA and need one more step

C. BA

The Insert algorithm of Unsorted Array Structure has the following steps, put the following steps in correct order (page 66) Step A: index next is incremented by one to prepare for the next insertStep B: A new node object is allocated with its contents initialized to the contents of the node to be insertedStep C: A reference to it is placed into the array at data[next] A. ABC B. BAC C. BCA D. CBA

C. BCA

The following is not true about Binary Search : A. Binary Search algorithm is a technique for rapidly finding a data item stored in an array B. Binary Search algorithm will return the index of the array elements where the search value is stored C. Binary Search algorithm can be applied on the unsorted arrays D. Binary Search algorithm assumes that the data in array are already sorted. in ascending order

C. Binary Search algorithm can be applied on the unsorted arrays

Basic operations that are supported by built-in structure array support are (page 63) A. Fetch and Delete B. Insert and Delete C. Fetch and Update D. Delete and Update

C. Fetch and Update

Put the terms, node, field and data set in size order from small to large: (page 11-12) A. Data set, field, node B. Field, data set, node C. Field, node, data set D. Node, data set, field

C. Field, node, data set

Which one is not correct about the object (page 40)? A. Object is an instance of a class B. After an object is declared, the client code can invoke any public accessible methods declared in the class by using objectName.methodName() C. In Java, accessing information in objects requires only one memory access as primitive variable (page 40) D. In Java, accessing information in objects requires two memory

C. In Java, accessing information in objects requires only one memory access as primitive variable (page 40)

Which of the four basic operations do the restricted structures support? A. Update B. Fetch C. Insert D. none of above

C. Insert

Nodes A, B and C are placed on a stack in the order first A, then B and finally C, if invoking pop method on this stack, which node will be popped A. Node A B. Node B C. Node C D. You need to determine which node to pop

C. Node C

Which statement is not correct about data? A. Data is information B. Data can be input data or output data C. Studies show that programs spend only 10% of their execution time for searching through memory to locate the data they process D. The source of data can be any device attached to a computer system

C. Studies show that programs spend only 10% of their execution time for searching through memory to locate the data they process

Class abstraction is: A. We do not need to know anything about the data structure to use it B. We do not need to know what data structure about to use it C. We do not need to know the implementation details of a data structure in order to use it D. We do not need to know what the data structure is about to use it

C. We do not need to know the implementation details of a data structure in order to use it

Generic Data Structure is: (page 106) A. a data structure can store any kind of node and can be used in an application B. a data structure could not only be used to store the data for a telephone listing application but also an employee record application, a store inventory application or any other type of data application without modifying its code C. a and b D. none of above

C. a and b

The way that a class user relates to the class is called the

Class interface

What is autoboxing?

Converting a primitive to the corresponding wrapper class when needed

Which one is not correct about the class? A. Class is a programmer-defined type B. Class consists of data definitions and methods that operate on the data C. Public class allows a method in any application to declare a reference variable of this class type D. Class is a primitive data type that Java defines in the Java library

D. Class is a primitive data type that Java defines in the Java library

Update algorithm of Unsorted Array Structure with the key field as targeKey will combine two following operation in this order (page 71) A. Fetch - Insert B. Insert - Fetch C. Insert - Delete D. Delete - Insert

D. Delete - Insert

Which one is not correct about encapsulation? A. Encapsulation helps to reduce the cost of the software development. and maintenance B. Encapsulation produce the code is more easily reused C. Encapsulation is the idea that we write the code in a way that establishes compiler enforced protocols for accessing the data that the program process D. Encapsulation provides the code such that all the fields can be access from everywhere outside the class

D. Encapsulation provides the code such that all the fields can be access from everywhere outside the class

Algorithm speed will consider the following factors: A. relative speed of the algorithm B. absolute speed of the algorithm C. do not need to consider anything D. a and b

D. a and b

programs are ______ _______ + _________

Data Structures + Algorithms

What is a stack?

Data structure in which elements are "stacked" on top of one another. Only the element on the top of the stack may be accessed. LIFO: Last In First Out.

What is a Link object composed of?

Data, and a next. The next is a reference to another link object (or null)

Which one is not correct for the speeds of Unsorted Array Structure operations A. Insert: O(3) B. Delete: O(log2n) C. Fetch: O(n) D. Update: O(2n + 3)

Delete: O(log2n)

What is the third basic rule of recursion?

Design rule: assume recursive calls work without tracing it all out

There are two Access Modes that are used to specify the node to be accessed: A. The node number mode B. The type of the node mode C. The key field mode D. a and b E. a and c

E. a and c

What is a queue?

Essentially a line, uses FIFO: First In First Out. Used for print queue. No "cuts" in line.

A queue is known as a

FIFO- First in first out; a queue is another kind of simplified list; add at back, delete/peek at the front; Its like a line at a grocery store; the first one in is the first one that comes out.

1. Specifications indicate how to implement ADT operations, but not what the operations do

False

10. Classes that use dynamically allocated memory can depend on the compiler-generated destructor.

False

12. A recursive version of toVector is complicated and requires invocation of the copy constructor.

False

14. A link-based implementation requires less memory than an array-based implementation.

False

2. Before you can assign headPtr a value, you must first create a new Node object.

False

2. In an array based implementation of a stack, the stack can grow and shrink dynamically.

False

4. Data structures for an ADT can be determined at any time during the process of specifying its operations.

False

The built-in data structure array is fast and its memory overhead is low TRUE The built-in data structure array supports the key field access mode

False

The pop function in the stack retrieve the value from the top of the stack. It does not removes it.

False

The pop function in the stack retrieve the value from the top of the stack. It does not removes it. True False

False

The queue is initialized with the top = -1 and data[ i ] = null where i = 0 to size True False

False

Traversing a list of N items using the following loop is O(N) if wordlist is an ArrayList, but O(N2) if it is a LinkedList. for (String str: wordlist) { System.out.println(str); }

False

1. According to the principle of information hiding, a module should be completely isolated from other modules.

False.

1. If 5 items are added to a stack, the first item to be removed from the stack is the first item that was added to the stack.

False.

2. A stack has a first in, first out property.

False.

3. A binary search starts at the beginning of the collection of items.

False.

3. An abstract data type is another name for a data structure.

False.

3. The peek operation of the ADT stack changes the stack.

False.

4. An iterative method always calls itself.

False.

5. If the characters in a string are added to a stack one at a time, characters removed from the stack will occur in the order in which they appear in the original string.

False.

5. In practice, recursion should be used even when a problem has a simple iterative solution.

False.

7. By default, all members in a class are public.

False.

9. The binary search algorithm can be applied to an unsorted array.

False.

In java, new returns a pointer, not a reference. (T/F)

False. In Java, new returns a reference as opposed to a pointer as C++ does.

Bubble, selection, and insertion sort are all unstable. (T/F)

False. They are all stable.

Which one is not correct for the speeds of Unsorted-Optimized Array Structure operations? A. Insert: O(3) B. Delete: O(<=n) C. Fetch: O(log2n) D. Update: O(<= n + 3)

Fetch: O(log2n)

What is a circularly linked list?

I circularly linked list has a tail element that points back to the head, so it goes in one infinite loop.

What does a destructor do?

Is supposed to relinquish any owned resources the of "deleted" object --Called during delete

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

A Stack is known as

LIFO- Last in First out; can only add, remove and delete from one end

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)

What is the second basic rule of recursion?

Making progress: each recursive call makes progress towards the base case

What is faster N log N or N?

N

Are collections covariant in java?

No, collections are not covariant in java.

What is the efficiency of the following recursive function: public static long fib(int n) { if (n <= 1) return 1; else return fib( n - 1 ) + fib( n - 2); }

O(2^n) because each call to factorial produces two more calls to factorial

What is the big-Oh of a sequential search?

O(N)

interpolation worst case

O(N)

What is the efficiency of the following recursive function: public static long factorial(int n) { if (n <= 1) return 1; else return n * factorial( n - 1 ); }

O(N) because each call to factorial produces one other call to factorial.

What is the efficiency of the following code using a LinkedList? public static void makeList2( List<Integer> lst, int N) { lst.clear(); for ( int i=0; i<N; i++) lst.add( 0, i ); // add to front of list }

O(N) because inserting into an ArrayList at the beginning is O(1)

What is the Big-O notation of 2N^2 + N + 5

O(N^2)

sum=0; for (i=0;i<n;i++) for (j=0;j<i;j++) sum++;

O(N^2)

sum=0; for (i=0;i<n;i++) for (j=0;j<n;j++) sum++;

O(N^2)

f(n) = 4log(n)

O(log(n))

What is the typical efficiency of an algorithm that divides the problem size by a fraction?

O(logN)

interpolation average case

O(log^2 N)

Insertion sort best case

O(n)

What are the average, best, and worst cases for bubble sort? (Give overall, swaps, and compares.)

Overall: Average - O(n^2) Best - O(n) Worst - O(n^2) Swaps: Average - 1/4n^2 Best - 1 Worst - 1/2n^2 Compares: Average - 1/4n^2 Best - N Worst - 1/2n^2

What are the average, best, and worst cases for insertion sort? (Give overall, swaps, and compares.)

Overall: Average - O(n^2) Best - O(n) Worst - O(n^2) Swaps: Average - 1/8n^2 Best - 1/2n Worst - 1/4n^2 Compares: Average - 1/4n^2 Best - N Worst - 1/2n^2

What are the average, best, and worst cases for selection sort? (Give overall.)

Overall: Average - O(n^2) Best - O(n^2) Worst - O(n^2)

Which type of error that occurs if a Push operation is invoked on a full stack?

Overflow error

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);

The operation for removing an entry from a stack is traditionally called:

Pop

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 is proof by contradiction?

Proof by contradiction assumes that the theorem is false, and then shows that that false theorem cannot be possible.

What is proof by counterexample?

Proof by counterexample proves something wrong by giving one example that shows that the statement is false.

What is the difference between Arraylists vs. LinkedLists?

Shifting indexes in array lists will affect the O(N), a linked lists will not do this.

O (Big-O)

T(N) = O(f(N)) => T(N) <= c(f(N)) ; c is constant, N >= No

Θ (Theta)

T(N) = Θ(f(N)) => T(N) = O(f(N)) and T(N) = Ω(f(N))

What is the best case for sorts?

The data is sorted already

What is a geometric series?

The sum of the terms of a geometric sequence

The Java syntax for two dimension array element is x[i] [j]. Which one is NOT correct: a. index I and j always start at zero b. i represents the row number, j represents the column number c. There are r rows and c columns in the array x then xrc is the last element d. All of above are correct

There are r rows and c columns in the array x then xrc is the last element

Growth rates are equal

Theta

What symbol do we use to represent an equal growth of upper and lower bounds of an algorithm?

Theta

What is the purpose of an iterator?

To preserve abstraction by hiding the details of certain functions such as next and remove.

All the nodes of an array data structure are located on contiguous memory address. Therefore, the nodes are stored sequentially based on the node number.

True

All the nodes of an array data structure are located on contiguous memory address. Therefore, the nodes are stored sequentially based on the node number. True All the programmer-defined Array structures access nodes by using the key field mode

True

When working with stacks and queues, it is best not to use arrays, but to use Linked Lists instead. (T/F)

True

Working with built-in array data structure, Insert and Delete operations cannot be allowed

True

T/F GenericMemoryCell<Integer> m = new GenericMemoryCell<Integer> ( ); can be written as GenericMemoryCell<Integer> m = new GenericMemoryCell< > ( );

True, this shows a use of the diamond operator, once the integer has already been specified it does not need typing again

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 nullptr?

a pointer that points to nothing

Best-case is often ______

atypical, not useful

autoboxing

automatically inserts a wrapper; conversion from primitive type to wrapper class

What is the first step of an inductive proof?

base case

lower bound

best case, least amount of work performed

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

java collections

common data structure known as Collections API that stores objects of the same type

array, vector, and deque run in

constant time

generic methods

data is inferred based on the type passed to it (i.e.: public static <AnyType> ... )

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

whenever you use new you must use ______ or else you could cause a ________

delete.....memory leak

What is cohesion?

describes how well a unit of code maps to an entity or behavior

What is coupling?

describes the interconnectedness of classes in a loosely coupled system: each class is largely independent and communicates with other classes via a small, well-defined interface

arithmetic series

difference between successive terms is constant

Sequential searching

examine 0th element, then 1st, and so on...

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

queue

implemented with an array and index positions

one iteration of _______________ could be slower than complete ______________

interpolation.....binary serach

public static <AnyType extends Comparable<AnyType>> AnyType findMax(AnyType [] arr) If Shape implements Comparable<Shape>, it is accepted, but if Square extends Shape and implements Comparable<Shape>, _____________

it is not

What can the Collections interface be used for?

java.util.Collections provides a variety of static methods on Lists static int binarySearch(List<T> list, T key) static T max(List<T> list); static T min(List<T> list); these methods can be called on both ArrayLists and LinkedLists

Java code to search for key and delete it from array?

key = 55; for (j = 0; j < nElems; j++) if (arr[j] == key) break; for (int k = j; k < nElems; k++) arr[k] = arr[k+1]; nElems--;

Which of the following stack operations could result in stack underflow?

pop

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).

geometric series

series with a common ratio between successive terms

Big O of binary search?

O(log N)

What is the big-Oh of a binary search?

O(log N), faster than O(N), if the number of operations required to solve a problem is proportional to the logarithm of the size of the problem

binary search

O(log₂N) - for sorted data - check middle and search higher/lower - not good on linked implementations

What is complexity of insert, delete, and find in a linked list?

O(n)

What is the typical efficiency of an algorithm that reduces the problem set by a constant?

O(n)

f(n) = 3n + 1

O(n)

linear search

O(n) - for unsorted data, go item by item until found

Bubble Sort Worst case

O(n^2)

Insertion Sort Worst Case

O(n^2)

Selection Sort Worst and Best Case

O(n^2)

f(n) = 60n^2 + 5n + 1

O(n^2)

What is the formal definition of Big-O notation?

O: T(N) = O(f(N)) means that T(N) <= cf(N) for some constant c and for N >= n0.

What symbol do we use to denote lower bounds with algorithms?

Omega

What is a key?

One or more fields used to uniquely identify a record. Primary key - a single (distinguished) field.

Algorithm Details

Operations on data Insertion and removal of elements Rearranging data (reverse, sort, merge) Searching data

9. Highly coupled modules should be avoided.

True

9. The entries in a bag have no particular order.

True

Array is a built-in data structure to store values of the same type that is called a homogeneous structure

True

Arrays are contiguous blocks of memory. (T/F)

True

Bubble, insertion, and selection sorts should not be used for more than 1000 data records. (T/F)

True

Give an efficient circular array-based queue Q capable of holding 10 objects. After the following code is executed: for (int k = 1; k <= 7; k++ ) Q.enqueue(k); for (int n = 1; n <=7; n++ ) Q.enqueue (Q.dequeue()); The result on the queue as follows: 0 1 2 3 4 5 6 7 8 9 4 5 6 7 1 2 3

True

Ordered array stores values in key sequence (T/F)

True

Binary search midpoint equation

first + ((last-first)/2)

Big-O

upper bound - will grow no faster than this

O (Big-O)

upper-bound (possibly equal)

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

circular linked list

links the last node to the first node

What is faster: log N or log^2 N

log N

How do you solve for log with only base 10?

log base 2 of 16 = log base 10 of 16 / log base 10 of 2

What does log base 2 of a+b equal?

log base 2 of a * log base 2 of b

What does log base 2 of a-b equal?

log base 2 of a / log base 2 of b

what is faster: log^2 N or N

log^2 N

logaB =

logcB / logcA

X^a = B if and only if ______

logxB = A

Big Omega

lower bound

Ω (Omega)

lower bound (possibly equal)

sentinel nodes

marks beginning or the end an empty list is 2 nodes

.size() vs ->size

use -> when using pointers and function calls, don't use .

What are the advantages of an ordered array? (1)

1) Quicker search than unsorted array

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

What methods are needed in a queue? (10)

1) Constructor for user to specify max size 2) insert - insert or add an item 3) remove - delete or remove an item 4) peekFront - get value w/o removing it 5) isEmpty - check if empty 6) isFull - check if full 7) size - current number in queue

What methods are needed in a stack? (9)

1) Constructor to allow user to specify max size of stack. 2) push - insert or add an item 3) pop - delete or remove an item 4) boolean isEmpty() 5) boolean isFull() 6) peek - same as pop followed by push 7) size - current number on stack 8) maxSize - how many can I put on it? 9) grow - become a larger structure

What are some special cases regarding Linked Lists?

1) Dealing with an empty list 2) insert or delete at beginning 3) insert or delete at end

What are the four basic things a data structure should handle? (4)

1) How do I insert? 2) How do I retrieve? 3) How do I delete? 4) How do I sort?

What are the three main operations an ordered array performs? (3)

1) Insert - find location and move all other items "up" 2) Delete - find location and move all other items "down" 3) Search - linear, as before, or binary search (repeatedly divide search space in half)

What are the three main operations an array can perform? (3)

1) Insert - place item at the end of the array 2) Search - start at beginning and test each value 3) Delete - "Search" for item. Must move all "higher" items down to fill vacancy.

Big-O complexity from best to worst? (7)

1) O(1) 2) O(log n) 3) O(n) 4) O (n log n) 5) O(n^2) 6) O(2^n) 7) O(n!)

On average and with duplicates, what is the runtime for searching, inserting, and deleting in an unordered array? (3)

1) O(n) 2) O(1) 3) O(n)

On average and with no duplicates, what is the runtime for searching, inserting, and deleting in an unordered array? (3)

1) O(n/2) 2) O(1) 3) O(n/2)

Why not use arrays for everything? (3)

1) Other data structures are more efficient for certain operations 2) Potential of overflow is always a problem 3) Doesn't always model the problem well

What are the advantages of a stack? (1)

1) Provides last in, first out access

What is a Java Collection?

A Java collection is an interface which you can implement in your class that provides the class with special functions such as size, isEmpty, clear, contains, add, remove, and an iterator.

What is a list?

A List is an ordered collection of elements of a single data type. Elements added to a List are assigned an implicit index, and therefore, Lists can contain non-unique values (i.e. elements can be duplicated within a List).

What is a Queue?

A collection of data kept in the order it was collected. You can only add from the back and remove from the front (line at BestBuy)

What is a database?

A collection of records, a file (table). In Java, a collection of objects.

What is a comparator?

A comparator is a Java class that compares two objects. Instead of having the comparison logic live inside of the class, we separate it out so we can pass it to other functions.

What is an Algorithm?

A self-contained step-by-step set of operations to be performed

What is an arithmetic series?

A series in which the difference between successive terms is constant.

set

A set maintains a collection of unique values called keys

What is a record?

A specific unit of closely related information A line in a table of information. A collection of fields In Java, an object.

What is a stack?

A stack is a last in first out data structure. It's like a stack of plates, the most recent one to be put on the top of the stack of plates will also be the most recent one to take off.

What is the activation record or the stack frame?

A stack that keeps track of variables, arguments, and return addresses anytime a function call is made in code.

What is the fourth basic rule of recursion?

Compound interest rule: don't duplicate work already performed in a previous call

Which one is true for Linear List? A. It is a collection of n nodes if there is a unique first node N1, unique last node Nn and only one node in the list B. It is a collection of n nodes if there is a unique first node N1, unique last node Nn and for any other node, only one node comes before it and only one node comes after it C. It is a collection of n nodes if there is a unique first node N1, unique last node Nn and for any other node, it can have one or more nodes come before or after it D. None of above

B. It is a collection of n nodes if there is a unique first node N1, unique last node Nn and for any other node, only one node comes before it and only one node comes after it

A = 23n + 36n2 B = 6 + nlog2(n) + n C = log2n + 36n2 Which one of the following is correct? A. TA = O(n2) TB = O(n) TC = O(log2n) B. TA = O(n2) TB = O(nlog2(n)) TC = O(n2) C. TA = O(n2) TB = O(+ nlog2(n)) TC = O(log2n) D. TA = O(n2) TB = O(n) TC = O(n2)

B. TA = O(n2) TB = O(nlog2(n)) TC = O(n2)

What symbol do we use to denote upper bounds with algorithms?

Big-O

What is a good example of a O(logn) algorithm?

Binary search because it splits the problem set into two parts at each step.

How does bubble sort work?

Bubble the highest (or lowest) to the top (or bottom). Then bubble the 2nd highest (or lowest). Then the 3rd. And so on...

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

The Delete algorithm of Unsorted-Optimized Array Structure has the following steps, put them in correct order (page 67 and 81) Step A: Move the last node reference into the deleted node's position. Step B:Use sequential search to locate the node to be deleted, the search begins at element zero and terminates when the node with the given key is located. A. AB B. AB and need another step C. BA D. BA and need another step

C. BA not correct

Which one is correct operation list of ArrayList (page119)? A. Insert, Update, Fetch, Remove B. Add, Update, Fetch, Remove C. add, get, remove and set D. add, get, delete and set

C. add, get, remove and set

What is type erasure?

Checks for type on generic classes are removed at compile time to reduce overhead because the compiler already knows the types are correct.

What is the third step of an inductive proof?

Conclusion: by induction, the theorem holds for all cases i.e. the minimal case and all its successors

What is Big-O rule #3?

Consecutive statements add (which means the maximum one is the one that counts).

What is autounboxing?

Converting a wrapper class back to its primitive value when needed.

Assume 16 lines of code per person per day. Estimate a program will consist of 300,000 lines of code. If the burdened cost of a programmer's efforts is $150 per hour, determine the code of the program (page 10) A. 45 million dollars B. 10 million dollars C. 90 million dollars D. 22.5 million dollars

D. 22.5 million dollars

There are 2 nodes stored in a linear list. Which node comes just before and just after the first node? A. None and last node B. Node 0 and Node 2 C. None and Node 2 D. A and C

D. A and C

Array member of the Built-in Structure array: (page 60-61) A. is stored in contiguous memory B. has unique ordinal subscript could be thought of as node number C. has nodes that are stored sequentially based on the node number D. All of above

D. All of above

Big-O analysis is __________ A. An analysis technique that is used to set a bound of the upper limit of a mathematical function. B. An analysis technique that is based on the assumption that one of the term of the function will dominate all but negligible portion of the value of the function as the independent variable gets large. C. An analysis that is used to evaluate functional relationships D. All of above

D. All of above

Insertion Sort

Each items is take in turn, compare to the items in a sorted list and placed in the correct position.

How does selection sort work?

Each pass locates (selects) the smallest item remaining in unsorted portion, then puts it in the correct location.

2. The language Algebraic Expressions is the set of strings that meets certain rules of syntax and that definition also gives the rules of the syntax.

False

4. Like an array-based implementation, a link-based implementation's insertion and removal operations will need to move data items.

False

4. The stricter a definition, the harder it is to recognize a syntactically legal expression.

False

5. A class need not validate data given by client code. According to the author, the client code should do that.

False

6. Choices made during the implementation process have no effect on execution time of your code.

False

6. Even though you have allocated memory by using new, there is no need to deallocate it with the delete command.

False

6. Subproblems that a recursive search solution generates need not reach a base case.

False

7. According to the text, when adding a first entry to an array, always place it in the first element, the element whose index is zero.

False

8. A class can have multiple destructors.

False

8. A highly cohesive module is less robust.

False

8. Little relationship exists between mathematical induction and recursion.

False

8. The client of a class can access the class's private members directly by use of a password.

False

A real-world example of the queue data structure can be seen in the cafeteria trays, where the last tray placed onto is the first tray removed.

False

A stack will be initialized with top = 0 and data[i] = null with i = 0 to size True False

False

What is an example of proof by contradiction?

For example, let's say that 2 even numbers always add up to make an even number. To prove this correct, we assume that the sum of 2 even numbers makes an odd number: 2a + 2b = 2c + 1. However, when we factor out a two from the left side, we get 2(a+b) = 2c+1. This shows that an even number equals an odd number, which is not possible.

What is Big-O rule #1?

For-loops. Number iterations (n) times the statements inside.

sum=0; for (i=0;i<n;i++) for (j=0;j<i*i;j++) for (k=0;k<j;k++) sum++;

O(N^5)

What is the typical Big-O of divide and conquer solutions?

O(NlogN)

Why is this good code? public class GenericMemoryCell<AnyType> { public AnyType read() { return storedValue; } public void write(AnyType x) { storedValue = x; } private AnyType storedValue; } public class TestGenericMemoryCell { public static void main(String [] args) { GenericMemoryCell<Integer> m = new GenericMemoryCell<Integer> ( ); m.write( 37 ); int val = m.read(); System.out.println("Cell contents: " + val ); } }

If this is anything but an integer you get a compile error as opposed to runtime error

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&);

What is Big-O rule #4?

If-else statements are the test plus the larger of the two branches.

What is the second step of an inductive proof?

Inductive step: a. inductive hypothesis: assume theorem holds for all cases up to some limit k, b. prove the next case for example, k+1

What is inheritance?

Inheritance is a mechanism in which one object acquires all the properties and behaviour of another object of another class. It represents IS-A relationship. It is used for Code Resusability and Method Overriding.

What does a constructor do?

Initializes the object to some defined state --Called during new

Which of the four basic operations do the restricted structures support?

Insert

Which one is NOT correct about ArrayList (page 118)? A. ArrayList is class provided in Java Application Programmer Interface (API) B. ArrayList object can expand at run-time beyond its initial size to accommodate unanticipated Insert Operation C. ArrayList boston = new ArrayList();//initial size defaults to 10 nodes D. Insert, Fetch, Delete, and Update are 4 operations of ArrayList

Insert, Fetch, Delete, and Update are 4 method names of ArrayList

Which one is not correct for the speeds of Sorted Array Structure operations

Insert: O(3)

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

Which statement is NOT correct for Built-in Structure Array: (page 60) A. All of the values stored in the variable are of the same type B. Each array member is distinguished by the variable name and a unique ordinal subscript C. It can grow and shrink, therefore, Insert and Delete operation would be allowed D. There is a minimum and maximum value of the subscript

It can grow and shrink, therefore, Insert and Delete operation would be allowed

What is an example of proof by counterexample?

Let's say the function says that the nth Fibonacci number is less than n^2. However, the 11th Fibonacci number is 144, and 11^2 is 121. Therefore, here is a proof by counterexample.

Do java generics require casting and why?

No they do not require casting because it is the java compiler that checks the types, not calculated at runtime.

Can you declare an array like this if Student is a subclass of Person: Student[] students = new People[];

No you cannot because you are creating a more specific array from a more general object.

Nodes A, B and C are placed on a Queue in the order first A, then B and finally C, if invoking dequeue method on this queue, which node will be dequeued

Node A

Nodes A, B and C are placed on a stack in the order first A, then B and finally C, if invoking pop method on this stack, which node will be popped

Node C

bubble sort

O(N²) compare adjacent values, swap to get largest values to the end of the array

selection sort

O(N²) find the next largest/smallest and swap to proper position (don't slide)

Upper bound (not equal)

Little o

bubble sort

Moving through a list repeatedly, swapping elements that are in the wrong order.

What is faster: N^2 or N log N

N log N

What is faster N^3 or N^2?

N^2

What is faster: 2^N or N^3

N^3

What is Big-O rule #2?

Nested for-loops. Statements inside times the product of loop sizes.

insertion sort

O(N²) take an element and put it in the proper position relative to everything to the left of it

Consider this method header: public static <AnyType extends Comparable<? super AnyType>> AnyType findMax(AnyType [] arr)

Now if Square extends Shape and implements Comparable<Shape>, it is accepted, since Shape is a superclass of Square. Super says the comparable can be on my super class

What is the big-Oh of a merge and quick sort?

O (N log N), faster than N^2, so doubling the list size increases the work by a little more than double

The speed of Enqueue operation of Queue structure is:

O(1)

The speed of Push operation of Stack structure is:

O(1)

f(n) = 4

O(1)

What methods does the LinkedList use from the List interface?

O(1) add/remove at beginning/end, add/remove if have access to location O(N) add/remove from middle, access/search

What methods does the ArrayList use from List interface?

O(1) add/remove at end, Access O(N) search, add/remove from beginning/middle

What is the efficiency of the following code using an ArrayList? public static void makeList2( List<Integer> lst, int N) { lst.clear(); for ( int i=0; i<N; i++) lst.add( 0, i ); // add to front of list }

O(N^2) because of the main loop as well as the time it takes to shift everything in the array over 1 on each insert.

What is the big-Oh of a insertion and selection sort?

O(N^2), faster than log N so doubling the list size quadruples the amount of work

int x = 0; for (int i = 0; i < N; i++) for (int j = i + 1; j < N; j++) for (int k = j + 1; k < N; k++) x++;

O(N^3)

sum=0; for (i=0;i<n; i++) { for (j = 0; j<n*n; j++){ sum++; } ) }

O(N^3)

sum=0; for (i=0;i<n;i++) for (j=0;j<n*n;j++) sum++;

O(N^3)

what is the Big-O notation of N^3 + N^2

O(N^3)

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...

Tell what of the following does the acronyms FIFO describes for:

Queue

Given an empty Queue Q, what does it look like after the following operations? Q.enqueue(5); Q.enqueue(2); Q.dequeue(); Q.enqueue(3); Q.dequeue();

Queue Q stores 3

Given an empty Queue Q, what does it look like after the following operations? Q.enqueue(5); Q.enqueue(2); Q.dequeue(); Q.enqueue(3); Q.dequeue(); A. Queue Q stores 3 B. Queue Q stores 5 C. Queue Q stores 2 D. Queue Q stores none of above

Queue Q stores 3

What is the average case for sorts?

Random data in no particular order.

What are the four rules of Big-O notation?

Rule 1: For-loops. Number iterations (n) times the statements inside. Rule 2: Nested for-loops. Statements inside times the product of loop sizes. Rule 3: Consecutive statements add (which means the maximum one is the one that counts). Rule 4: If-else statements are the test plus the larger of the two branches.

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

What is the worst case for sorts?

Sorted in reverse order.

o (Little-O)

T(N) = Θ(f(N)) => T(N) = O(f(N)) and T(N) ≠ Ω(f(N))

Ω (Omega)

T(N) = Ω(f(N)) => T(N) >= c(f(N)) ; c is constant, N >= No

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)?

The built-in data structure array is fast and its memory overhead is low

TRUE

Describe the ability of Peek operation on the Expandable Model of a stack

The ability to pop a node from the stack without deleting it from the structure

Which one is not correct about Inheritance?

The classA is called the parent class and the classB is called the child class

What are the 4 steps of induction?

The four steps of induction are proving the base case, creating an inductive hypothesis, prove the k+1 case, and forming a conclusion.

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.

What happens if you remove an object from a collection while it is being iterated over?

The iterator will become invalid and you will no longer be able to loop over the elements.

Will the java compiler allow you to do this? If so, will it run? Person[] arr = new Employee[5]; arr[0] = new Student();

The java compiler will allow you to write this code however it will crash because Student is not an employee.

9. According to the text, you must write a destructor if your class allocates memory dynamically.

True

Why is this bad code? public class MemoryCell { public Object read() { return storedValue; } public void write(Object x) { storedValue = x; } private Object storedValue; } public class TestMemoryCell { public static void main(String [] args) { MemoryCell m = new MemoryCell ( ); m.write(new Integer(5)); Integer wval = (Integer) m.read(); int val = wval.intValue(); System.out.println("Cell contents: " + val ); } }

There would be a runtime error if you cast the object the wrong way with m.read();

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 does this method header accept: public static double area(Collection<? extends Shape> arr)

This method header accepts any collection of shapes or collections that contains objects that are subclasses of shape.

1. A node can be dynamically allocated.

True

1. All programs are strings, but not all strings are programs.

True

11. The copy constructor for our bag class requires traversing the original linked chain and duplicating each node visited.

True

13. Access time is a constant for an array-based implementation.

True

15. The following method is recursive. template<class ItemType> void LinkedBag<ItemType>::fillVector(std::vector<ItemType>& bagContents, Node<ItemType>* curPtr) const { if (curPtr != nullptr) { bagContents.push_back(curPtr- >getItem()); fillVector(bagContents, curPtr- >getNext()); } // end if } // end fillVector

True

2. Generally it is unwise to define an entire class then attempt to test it

True

3. A given word, s, is a palindrome if and only if, the first and last characters of s are the same and s minus its first and last characters is a palindrome.

True

3. Generally speaking, a link-based implementation does not impose a fixed maximum size on the data structure.

True

3. In the link based implementation of the stack, both the method push and the copy constructor allocate new nodes.

True

3. The method getIndexOf should generally be declared as private.

True

4. An interface for a class that allows programmers to accomplish any reasonable task is called a complete interface.

True

4. Private data members are hidden from the client.

True

5. C++ arrays are data structures

True

5. For a link-based bag, the most convenient place to make an insertion is at the beginning of the chain.

True

5. It is possible to use one ADT to implement another ADT.

True

5. The following expression is a prefix expression + a b - c d

True

6. In both implementations of the class stack, the pop methods returned a value of type bool.

True

7. According to the author, the LIFO property of stacks seems inherently unfair.

True

7. The method clear cannot simply set ItemCount to zero.

True

7. The method toVector must "know" where the add has placed the entries.

True

7. You can use induction to prove that a recursive algorithm either is correct or performs a certain amount of work.

True

T/F T(N) = O(f(N)) means that T(N) <= cf(N) for some constant c and for N >= n0.

True

T/F T(N) = Θ (f(N)) means that T(N) = cf(N) for some constant c and for N >= n0.

True

T/F T(N) = Ω(f(N)) means that T(N) >= cf(N) for some constant c and for N >= n0.

True

The cost of executing merge sort on a list of N items can be characterized by the recursive function: Cost(N) = 2*Cost(N/2) + C1*N + C2

True

The first item placed onto a stack is always the last item removed from the stack

True

The linear list access function: AN = A0 + N * wthat is used to calculate the location of an element of the array from its node numberwhere Ao is the byte address of the first node called the base addressw is the node width (number of bytes per node) andN is the number of the node, starting from 0

True

The pop function in the stack retrieve the value from the top of the stack. It does not removes it. False Enqueue each letter of the word "Welcome" to the queue then print out the result of dequeue each letter from the queue will get the same word "Welcome

True

Traversing a list of N items using the following loop is O(N) if wordlist is an ArrayList, but O(N2) if it is a LinkedList. for (int i = 0; i < wordlist.size(); i++) { System.out.println(wordlist.get(i)); }

True

1. A program can use the operations of the ADT stack without knowing how the operations are implemented.

True.

1. A recursive solution solves a problem by solving a smaller instance of the same problem.

True.

10. Any instance of a subclass can be used in a program anywhere that an instance of the superclass can be used.

True.

10. The base case for a recursive solution to finding the kth smallest item in an array cannot be predicted in advance.

True.

2. An iterative solution involves loops.

True.

2. Data structures are part of an ADT's implementation.

True.

4. A program can use the operations of the ADT stack without knowing how the operations are implemented.

True.

6. An application can use the operations of an ADT without knowing how the ADT is implemented.

True.

6. When constructing a recursive solution, you should assume that a recursive call's postcondition is true if its precondition is true.

True.

6. When infix expressions are converted to postfix expressions, the operands always stay in the same order with respect to one another.

True.

7. Every recursive method must have a base case.

True.

8. A recursive solution can have more than one base case.

True.

Big O notation

Used to state/compare efficiency of various algorithms by counting "operations"

What do we use to get around the fact that collections are not covariant in java?

We use wildcards to get around this problem.

X^a/X^b

X^(a-b)

(X^a)^b

X^(ab)

If a Person class has a subclass of Employee, then it is possible to write: Person x = new Employee(); But what about arrays? Person x[] = new Employee[5]; Can you make a person x array to be a new array of employee? Yes, this is allowed

Yes because of the "is a" relationship, these arrays in Java are "covariant", so the assignment works

Can you declare an array like this if Student is a subclass of Person: Person[] people = new Student[];

Yes you can because Student is a subclass of Person.

What is an example of a recursive function?

You can calculate x^y with the following function: public static int power(int x, int y) { if (n = = 0) // base case return 1; else return x * power(x, y-1); // recursive call } power(5,3) = 5*power(5,2) = 5 * (5 * power(5,1)) = 5 * (5 * (5 * power(5,0))) = 5 * 5 * 5 * 1 = 125

What are the restrictions of generic classes?

You cannot put primitive types into a generic class; you must use their class equivalents. You cannot instantiate a new generic object or array of generic objects. Cannot use class's type variable in static fields or methods. Not Allowed: GenericMemoryCell<String> arr[] = new GenericMemoryCell<String>[10]; // illegal

How do you delete a node from an arrayList?

You set the node to null and shift everything to the right of the node over by one.

How do you delete a node from a LinkedList?

You set the previous.next = node.next and the garbage collector will clean it up

What would happen if a string and not 30 were passed? public class GenericMemoryCell<AnyType> { public AnyType read() { return storedValue; } public void write(AnyType x) { storedValue = x; } private AnyType storedValue; } public class TestGenericMemoryCell { public static void main(String [] args) { GenericMemoryCell<Integer> m = new GenericMemoryCell<Integer> ( ); m.write( 37 ); int val = m.read(); System.out.println("Cell contents: " + val ); } }

You would get a compile time error

What is a class?

a class defines a new type of object

What is the Java Collections framework?

a collection is an object (i.e., data structure) that holds other objects

What is an Iterator?

a high-level abstraction of a value stored in a container

Which one is NOT the feature of the programmer-defined array structures (page 66) a. They are accessed in the node number mode b. They use an array of objects to store the data set c. They are fully encapsulated d. hey can store data sets of multiple nodes

a. They are accessed in the node number mode

Sequence Containers

access elements based off their position -- O(1) to O(N) index starts at zero array, vector, list, forward_list, deque

linked list

accessing an idem by index is O(N) because list needs to be traversed

array list

accessing item by index is O(1)

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

Algorithm examples

accumulate copy sort lower_bound, upper_bound nth_element partition

list interface

adding an item at the index location and and a position 0 at the front

array list

adding/removing from ____ is O(1)

enqueue

advances back and is known as in insertion in a queue

dequeue

advances to the front and is known as a deletion in a queue

What does a List Interface do?

an interface defines a generic template for a class --specifies the methods that the class must implement --but, does not specify fields nor method implementations

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>

You ______ create a new instance of a generic type

can't

You ________ create an array of generic type

can't

Can you always perform interpolation search? Why or why not?

can't be used on data that isn't uniformly spaced apart

You _________ use a class's type variable in static field's or methods

cannot

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)

type class

cannot use ____ variable in static variables and methods

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

What are things that are in a class?

fields are variables that belong to the object (and maintain its state) note: "this." is optional, but instructive methods define the actions that can be performed on an object typically public, so can be called by client code a constructor is a special method that automatically initializes the object when it is created can have more than one constructor

euclid's algorithm

finding the greatest common divisor of the two values gcd(15,5) > 5 50 % 5 = 5 running time is O(log(N))

A class encapsulates two things:

data (data members {Java: instance variables}) operations (member functions {Java: methods})

What is the fastest function?

c Constant

What are the different Big-O levels of efficiency?

c Constant log N Logarithmic log2 N Log-squared N Linear N log N N2 Quadratic N3 Cubic 2N Exponential

data structures

can be implemented differently, but should behave the same for the client

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];

What is the time required for an unordered array with duplicates to insert an element?

constant time. O(1).

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

unboxing

conversion of wrapper class to primitive type

In the implementations of the Stack operation presented in this chapter, what does the memory cell top store? a. the index of the array where the next push or the next pop will be performed b. the index of the array where the last push or the last pop was performed c. the index of the array where the next push or the last pop was performed d. the index of the array where the last push or the next pop is performed

d. the index of the array where the last push or the next pop is performed

Which operations for vector will (sometimes) invalidate iterators? Provide at least three.

erase? resize? reserve

inheritance

extends - subcategory (classes can only extend one parent, interfaces can extend many) implements - for interfaces, can do many

What are some examples of Big-O notation?

f(n) = 60n2 + 5n + 1 O(n2) f(n) = n(n+1)/2 O(n2) f(n) = 4 O(1) f(n) = n O(n) f(n) = 3n + 1 O(n) f(n) = 4log(n) O(log(n))

Give an efficient circular array-based queue Q capable of holding 10 objects.After the following code is executed:for (int k = 1; k <= 7; k++ ) Q.enqueue(k);for (int n = 1; n <=7; n++ ) Q.enqueue (Q.dequeue());The result on the queue as follows: true In the queue structure, the node is inserted at front and is removed at rear

false

In the queue structure, the node is inserted at front and is removed at rear

false

array list

growable implementation but costly

Θ (Theta)

growth rates are equal

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&&);

Is GenericMemoryCell<int> is legal or illegal?

illegal because you can't use primitive types for generics

For convenience of typing, the Java code replaces the subscript with the index for an array n elements. which one is NOT correct about it (page 63) A. x[i] reference for the element at the index i B. index i start by 0 C. index i ends by n D. the last element in array x is x[n-1]

index i ends by n

linked list

indexing is expensive and follows linked list implementation

For big O model we pretend memory is ________

infinite

Which vector operations are slow?

insert at the beginning

Syntax for sequential containers

insert, front, back.

linked list

insertion and removal is O(1)

stack

insertion is a push and deletion is a pop LIFO method

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.

What is the java code for selection sort?

int n = arr.length; // One by one move boundary of unsorted subarray for (int i = 0; i < n-1; i++) { // Find the minimum element in unsorted array int min_idx = i; for (int j = i+1; j < n; j++) if (arr[j] < arr[min_idx]) min_idx = j; // Swap the found minimum element with the first // element int temp = arr[min_idx]; arr[min_idx] = arr[i]; arr[i] = temp; }

What is the java code for bubble sort?

int n = arr.length; for (int i = 0; i < n-1; i++) for (int j = 0; j < n-i-1; j++) if (arr[j] > arr[j+1]) { // swap arr[j+1] and arr[i] int temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; }

What is the java code for insertion sort?

int n = arr.length; for (int i = 1; i < n; ++i) { int key = arr[i]; int j = i - 1; /* Move elements of arr[0..i-1], that are greater than key, to one position ahead of their current position */ while (j >= 0 && arr[j] > key) { arr[j + 1] = arr[j]; j = j - 1; } arr[j + 1] = key; }

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);

What is the Java syntax for creating an array?

int[] intArray = new int[100];

Interpolation Search mid equation

mid = ( ( val - A[first] ) / ( A[last] - A[first] ) ) x (last-first) more costly than binary search --expensive division

Which one is not correct for the speeds of Unsorted-Optimized Array Structure operations? Fetch: O(log2n) The initialized state of Unsorted Array structure n elements named data, which one is NOT correct: (page 66)

next is set to n-1

Can you have an array of a generic class?

no

What consists of Java arrayLists?

must specify content type when declare, capacity is optional (default is 0) can be dynamically expanded/reduced; can easily add/remove from middle

What is the difference between new and new[] ?

new points to the first element in the array new[] points to the whole array

Analyze the following code: public class GenericMemoryCell<AnyType> { public AnyType read() { return storedValue; } public void write(AnyType x) { storedValue = x; } private AnyType storedValue; } if there were a counter as a method, would it be AnyType as well?

no, it would just be an integer, you want 0 1 2 3 ... not a string or whatever else

Is a Fibonacci call a good use of recursion?

no, too much redundency

doubly linked lists

node pointing backwards and forwards

every _______ member function has a pointer to the invoking object

non-static

What does the following mean? comparable< ? super AnyType>

now any subclass of the type can be passed successfully

What is the time required for an unordered array with duplicates to find or delete an element?

num elements. O(n).

What is public vs. private?

private, so can only be accessed from within the class public can be accessed from outside of the class

Give an example of a Java generic class:

public class GenericMemoryCell<AnyType> { public AnyType read() { return storedValue; } public void write(AnyType x) { storedValue = x; } private AnyType storedValue; }

class template

template <typename T1, typename T2, ...> class ClassName { ... };

What is an example of a generic method in java?

public static <AnyType> boolean contains( AnyType [] arr, AnyType x )

What is the most efficient way to calculate the max subsequence sum of a list of numbers?

public static int maxSubSum4(int [] a) { int maxSum = 0, thisSum = 0; for( int j = 0; j < a.length; j++ ) { thisSum += a[ j ]; if(thisSum > maxSum ) maxSum = thisSum; else if (thisSum < 0) thisSum = 0; } return maxSum; }

What is the better way to loop over objects in Java?

public static void removeEvens( List<Integer> lst) { Iterator<Integer> itr = lst.iterator(); while ( itr.hasNext()) if ( itr.next() % 2 == 0 ) itr.remove( ); }

How do you not loop over a List in java?

public static void removeEvens( List<Integer> lst) { for ( Integer x : lst ) // implicit iterator if ( x % 2 == 0 ) lst.remove( x ); // iterator invalidated! }

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

queue

queue allows insertion to the back and removal from the front

method calls

recursion creates activation record with each recursive call

When is recursion useful?

recursion is useful when a task can be broken down into smaller, similar tasks functional recursion: a method directly or indirectly calls itself

Generic classes are seen by the compiler but are converted to _________________________________, this process is known as type erasure.

regular classes (called raw classes) during compilation.

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

O

relative growth rate where n => ∞ when f(N)/g(N) f(N) = o(g(N))

c

relative growth rate where n=> ∞ when f(N)/g(N) f(N) = Θ(g(N))

relative growth rate where n=> ∞ when f(N)/g(N) g(N) > o(f(N))

stack

stack allows access only at one end of the sequence, called top

nested classes

static - not specific to an instance of the class - do not have access to non-static variables of the class - outer class has access to the nested class ex: node

onsider the following pseudocode:declare a stack of characters while ( there are more characters in the word to read ) { read a character push the character on the stack } while ( the stack is not empty ){write the stack's top character to the screen pop a character off the stack} What is written to the screen for the input "carpets"?

steprac

What consists of java arrays?

stored contiguously, with each item accessible via an index must specify content type when declare, size when create once created, the size cannot be changed (without copying entire contents)

What are the benefits of a LinkedList? What makes it better than an ArrayList?

stores elements in a sequence but allows for more efficient interior insertion/deletion elements contain links that reference previous and successor elements in the list

big theta

tight bound - both big O and big omega

Why do we need a base case?

to prevent from running out of stack space memory

o (Little-O)

upper bound (not equal)

A stack will be initialized with top = 0 and data[i] = null with i = 0 to size false Give an efficient circular array-based queue Q capable of holding 10 objects.After the following code is executed: for (int k = 1; k <= 7; k++ ) Q.enqueue(k); for (int n = 1; n <=7; n++ ) Q.enqueue (Q.dequeue()); The result on the queue as follows:

true

T/F T(N) > o(f(N)) means that T(N) < cf(N) for some constant c and for N >= n0.

true

The first item placed onto a stack is always the last item removed from the stack True Which type of error that occurs if a Pop operation is invoked on an empty stack?

underflow error

What is the formal definition of Theta notation?

Ω: T(N) = Ω(f(N)) means that T(N) >= cf(N) for some constant c and for N >= n0.


Kaugnay na mga set ng pag-aaral

A-Level Edexcel History - Paupers and Pauperism

View Set

Operations with Complex Numbers / Quiz

View Set

prep u antineoplastic drugs and targeted therapies

View Set

Naturfag kapittel 6: Bølger og trådløs kommunikasjon

View Set

Chapter 54: Management of Patients With Kidney Disorders

View Set