18
Final Exam - Study Guide Simple Compilation of All Study Guides © FVCproductions - December 2014 Basic Definitions & Phrases abstract data type taken straight from the textbook a data structure is the underlying programming construct used to implement a collection abstractions ignores or hides certain details at certain times, e.g. collection is abstraction where details of implementation are hidden “abstract” in abstract data type means that there are many different ways of implementing data type algorithm step by step instructions on how to execute a program or set of instructions data structure memory structure with associated representation mapping, e.g. a collection is a type of data structure that acts as an object that gathers & organizes other objects a data type is specified by describing both its set of values & operations used for implementation implementing an abstract data type proceeds in 2 stages declaring necessary variables of data types writing methods & procedures to implement operations of data for given data types Arrays overview fixed size more efficient b/c it uses less memory easier to manage

CSC 251 - Final Study Guide

Embed Size (px)

DESCRIPTION

FVCproductionsCheck me out at fvcproductions.comWhere we upload for YOUR viewing pleasure,And are looking forward to future endeavor.Enjoy and spread the joy.Copyright 2014Don't forget to like and/or comment! :)

Citation preview

Final Exam - Study Guide 😓😓

Simple Compilation of All Study Guides© FVCproductions - December 2014

Basic Definitions & Phrases

abstract data type

taken straight from the textbook

a data structure is the underlying programming construct used to implement acollection

abstractionsignores or hides certain details at certain times, e.g. collection is abstraction wheredetails of implementation are hidden

“abstract” in abstract data typemeans that there are many different ways of implementing data type

algorithmstep by step instructions on how to execute a program or set of instructions

data structurememory structure with associated representation mapping, e.g. a collection is a typeof data structure that acts as an object that gathers & organizes other objects

a data type is specified by describing bothits set of values & operations used for implementation

implementing an abstract data type proceeds in 2 stagesdeclaring necessary variables of data typeswriting methods & procedures to implement operations of data for given data types

Arrays

overviewfixed sizemore efficient b/c it uses less memoryeasier to manage

collectionlinearcan add/remove at any position

Defining an array (character type) of a size 3 called array

char [] array = new char[10]

Ask user to enter 10 characters and assign each of the character into array

for (int i = 0; i < array.length; i++)

array[i] = keyboard.next().charAt(0);

Use the data in array to reverse a list called reverse so that the first element in the listcalled array is the last element in reverse

for (int i = 0; i < array.length; i++)

reverse[reverse.length – i] = array[i];

Write the first use way to use for-loop to print out all elements in the list called reverse

for (int i = 0; i < reverse.length; i++)

System.out.print(reverse[i] + “ ” );

Write the second use way to use for-loop to print out all elements in the list called reverse

for (char value : reverse)

System.out.print(value + “ ” );

Define a 3 by 4 floating point values array, called scores

double [][] scores = new double [3][4];

Assign the value for each cell in the array called scores tocolumnIndex * 20 / rowIndex

for (int row = 0; row < scores.length; row++)

for (int col = 0; col < scores[row].length; col++)

scores[row][col] = col * 20 / (double) row;

Print all the values in the array called scores

for (int row = 0; row < scores.length; row++) {

for (int col = 0; col < scores[row].length; col++)

System.out.print (scores[row][col] + “\t”);

System.out.println();

}

Write a findMax method which finds the maximum value in the data stored in scores

static double findMax(double [][] scores) {

double max = scores[0][0];

for (int row = 0; row < scores.length; row++)

for (int col = 0; col < scores[row].length; col++)

if (scores[row][col] > max)

max = myScores[row][col];

return max;

}

Comparing Stacks and Queues

Stacks and queues are similar data structures.They’re different only by how an item is removed firstBoth can be implemented as arrays or linked lists.

Properties of Stacks

overviewexample of a collection SDTsince stacks are lists, any list implementation will doLast In, First Out data structurecan be implemented as an arraycan only access the topharder to manage b/c only top can be accessed

defintiondata structure of ordered items such that items can be inserted and removed only at 1end (called the top )

diagram

conceptual implementationFirst In, First Out (FIFO)

add to rear and remove from frontoperations

push - adds item to stackpop - deletes item from stackpeek - looks at top item in stacksize - returns # of elements in stack by examining topisEmpty - tests for emptiness in stack by examining top

Stack Code & Algorithms

isEmpty

int top = -1; //or 0

public boolean isEmpty () {

return (top == -1);

}

isFull

public boolean isFull() {

return (top == size-1);

}

add to stack

public void add (int element) {

if (isFull() == true)

System.out.println("Stack full, cannot add element.");

else

stack[++top] = element;

}

1. check if stack is not full2. set top position of array to element being added to stack3. increment values of top and count (if partially filled array)

delete from stack

public int delete () {

if (isEmpty() == true)

System.out.println("Stack empty, cannot delete element.");

else

return stack[top--];

}

1. check if stack is not empty2. decrement top3. set return value to top position of array

print in order

public void printOrder() {

while(!isEmpty()) {

int value = remove();

System.out.print(value + " ");

}

}

find an element in stack

public boolean find(int element) {

System.out.print("Please enter element to find: ");

element = keyboard.nextInt();

for (int i = 0; i < size; i++) {

if (stack[i] == element)

return true;

}

return false;

}

Properties of Queues

overviewexample of a collection SDToperations: enqueue (add), dequeue (delete)

defintiondata structure of ordered items that can be inserted only at end (rear) and removed atother end (front)

diagram

conceptual implementationFirst In, First Out (FIFO)

add to rear and remove from frontoperations

enqueue - adds item to queue

dequeue - removes item from queuefirst - looks at top item in stack - so frontsize - returns # of elements in queue by examining topisEmpty - tests for emptiness by examining top

Queue Algorithms

shift queuesenqueue operation

1. save value at first index to item you want to enqueue2. increment size3. if array fills up, all n elements have to be copied to a new, larger array

dequeue operation1. save value at first index2. shift all elements left3. decrement size

circular queuesadvance queue indexes front (to delete an item) and back (to insert an item) bymoving them both clockwise around array

How To Choose Stacks Over Queues Or Vice-Versa

implementing a stack as an array is easy, but implementing a queue as an array is moredifficult because you have to dequeue from front and enqueue at endif you want to be able to add or remove values from any position, arrays are the way to gobecause any value can be accessed through indexesmain limitations of arrays is that they cannot be extended or shrunk so you want to use anarray when you know your max upper limitif you’re not sure how many values there will be in your data structure, then it’s better to notuse an array and stick with a linked list (ergo, queues)because arrays always have a fixed size

Real Examples in Tech Where Stacks Queues Are Used

examples of stacksCD storage casecafeteria traysbatteries in a flashlightcars in a single car garage

Towers of Hanoiexamples of queues

waiting line for a roller coasterhamburger processing line at Mickey D’sundo buttonvehicles on a toll bridgeluggage checking machinephone answering system for Apple’s customer support

Linked Lists vs Arrays

Arrayscan access any element directly via indexingall elements grouped togethersitting in 1 block of memorysize is fixed

Linked Listseach element sits in own block of memory (called node)nodes can only be accessed in sequential orderappears limitedsize varies - nodes allocated on need basislist elements can be easily inserted/removed without reallocation and at any point inthe listno random access to datano efficient form of indexing

Key Differencesunderlying layout of data in memoryhow individual elements are accessed

Linked Lists Properties

overviewa sequence of elements arranged 1 after another with each element connected tonext by a linkone of the simplest and most common data structurescan be used to implement other abstract data types

defintiondata structure of group of nodes that represent a sequence

diagram

above is a linked list with nodes that contain 2 fields - an integer value and a link to next tothe next node; last node linked to terminator symbol to signify end of list/null link

conceptual implementationeach node has data and reference (link) to next node in sequenceallows for insertion of removal of elements from any position in sequence

operations for singly linked listinsertion

deletion

traversal - going through entire sequence until reaching last nodeadvantages

dynamic data structure that allocates needed memoryeasy implementation for insertion and deletion operationsother data structures can be easily executed with linked listsreduce access time and can expand without more memory being used

disadvantagesusually wastes memory with pointers which requires extra storage spacenodes must be read sequentiallynodes stored in an in-contiguous manner, so more difficult to access individual nodesvery difficult to reverse traverse

Linked Lists Algorithms

constructor for an integer node in a linked list

public Int_Node (int initialData, Int_node initialLink) {

data = initialData; //integer value

link = initialLink; //reference to next node in list

}

define empty linked list

Int_Node head = null;

pseudocode1. representing empty list by storing null in head reference

keeping track of front node by using an Int_Node reference variable calledhead

add new node to empty list

head = new Int_Node(data, null);

pseudocode1. create new node for head2. place data in new node’s data field3. make head refer to null which is initial head value4. connect new node to head

add node to front of list

head = new Int_Node(newData, head);

pseudocode1. create new node2. place data ( newData ) in new node’s data field3. connect new node to front of list4. make original head refer to new head of linked list

Diagram showing how a node is inserted after an existing node Inserting node beforeexisting node cannot be done directly - instead you have to keep track of the previousnode and insert a node after that

adding anywhere but front

previous.link = new Int_Node(newData, previous.link);

while (prev.link != null) {

prev = head;

prev = prev.link;

}

pseudocode1. set a reference named prev (for previous) to refer to node which is just before

new node’s positionremoving node at head

head = head.link;

pseudocode1. directing head to node right next to it ( head.link ) so that original head is

removedremoving node anywhere

Removing node after given node - to find and remove a particular node, you still have tokeep track of the previous element

traverse through list

Int_Node pointer = head;

while (pointer != null) {

pointer = pointer.link;

}

pseudocode1. initializing pointer to reference head2. while loop that keeps going through entire list until pointer (or head ) is null

null implying that it’s reached the last node because the last node willalways have a null link since there’s nothing next to the last node so nolink so null link

3. pointer referenced to next node or pointer.linkprint list through traversal

Int_Node pointer = head;

while (pointer != null) {

System.out.print(pointer.data + " ");

pointer = pointer.link;

}

pseudocode

same as traversal algorithm but just printing out data of pointer as you go alongthe node sequence with pointer.data

Binary Trees 🌲🌲

treesa structure with unique starting point - root - where each node can have multiplechildren nodes, and a unique path exists from the root node to every other node

roottop node of a tree structure, a node with no parent

binary treestructure where each item is called a node and where each node can have a max oftwo children, left and right child node

diagram: leaf

node with no childrendescendant

child of a nodeancestor

parent of a nodebinary search tree

binary tree where value in any node is greater than or equal to value in its left childand any of descendants (nodes in left subtree) and less than value in its right childand any of its descendants (nodes in right subtree)

diagram: full binary tree

binary tree where all of leaves are on same level and every nonleaf node has 2children

complete binary treebinary tree that is full or full through next-to-last level, with leaves on last level as faras possible

balanced treeleft and right subtrees of any node are the same height

preordernode/root, left, right

inorderleft, node/root, right

postorderleft, right, node/root

FUN TIP I 🌟

a fast way to remember this is through the following, starting by writing r in the far left

then fill it out with L or R, representing left or right, as follows:

r L R - preorder

L r R - inorder

L R r - postorder

FUN TIP II 🌟

in-order traversal is probably easiest to see, because it sorts the values fromsmallest to largest (literally)

How to Delete A Binary Search Tree ␡

no successor1. if node is leaf, simply removed2. but if root is leaf, pointer to tree assigned null value

one successor1. parent node connected to sucessor node2. deleted node disposed of

two successors1. find logical predecessor (node in left subtree with largest value)2. logical predecessor replaces deleted node

Recursion 🚥🚥

recursive method is a method that calls itselfin many cases, recursive algorithms are less efficient than iterative algorithms

recursive solutions repetitivelyallocate memory for parameters and local variablesstore address of where control returns after method terminates

basically works like this:a base case is established

if matched, method solves it and returnsif base case cannot be solved

method reduces it to smaller problem (recursive case) and calls itself to solvesmaller problem

examples of recursion in real lifequick sort, merge sort, flowers,Towers of Hanoi, Fibonacci sequence, factorials

towers of hanoi fun pic:

example 1 provided - emptyVase 🍶

void emptyVase(int flowersInVase) {

if (flowersInVase > 0) {

//takes one flower

emptyVase(flowersInVase-1);

} else {

// vase is empty, nothing to do

}

}

example 2 provided - Recursion2

public class Recursion2 {

public void countItDown(int counter) {

if (counter == 0)

return;

else {

System.out.println("Count: " + counter);

counter--;

countItDown(counter);

System.out.println("" + counter);

return;

}

}

public static void main (String[] args) {

Recursion2 myRecursor = new Recursion2();

myRecursor.countItDown(5);

}

}

example 3 provided - count 20

count(n)

if (n > 0)

print n

count (n-1)

else

print done

count: n --> n = 3

count: (n-1) --> n = 2

count: (n-1) --> n = 1

count: (n-1) --> n = 0

example 4 - from textbook Foundations of Java

public class Recursive {

public static void message(int n) { //displays message n times

if (n > 0) {

System.out.println("This is a recursive method.");

message(n-1);

}

}

}

example 5 - from textbook Foundations of Java

public static int fib(int n) { // returns nth number in Fibonacci sequence

if (n == 0)

return 0;

else if (n == 1)

return 1;

else

return fib(n - 1) + fib(n - 2);

}

example 6 - from textbook Foundations of Java

public static int factorial(int n) { // returns factorial of non-negative argument

if (n == 0)

return 1;

else

return n * factorial(n-1);

}

example 7 - from textbook Foundations of Java

public static int gcd(int x, int y) { // returns greater common denominator of two arguments

if (x % y == 0)

return y;

else

return gcd(y, x % y);

}

Tips or Tricks? 🔎

Contact me @fvcproductions