COSC This week. Cloning. Cloning: Be Cautious. Cloning: the wrong type. Cloning: use super.clone()
|
|
- Kristina Lorin Johnston
- 6 years ago
- Views:
Transcription
1 This week COSC 3.3 Week 7, February 3, 4. Read chapter 3 Prepare for midterm on Thursday, Feb. 6 9:-: No aids (no calculators, aid sheet, etc) S ome multiple choice, some short answer, and a large programming question Deep/shallow cloning (all of Chapter will be on the midterm) Arrays, array lists, big O notation Cloning Cloning: Be Cautious Pair Pair Triple clone Triple x y x y z Pair // is cloned Triple or Pair? // clone somehow defined in class Pair; do we get the right clone? class Pair //not the standard Pair int x; int y; //override the clone method public Object clone() Pair cloned = new Pair(); cloned.x = this.x; cloned.y = this.y; return cloned; class Triple extends Pair int z; Pair ; public class PairTest public static void main(string[] args) S ystem.out.println( cloned instanceof Triple); //? S ystem.out.println( cloned instanceof Pair); //? //output is false true Cloning: the wrong type Cloning: use super.clone() Pair Triple x x y y z Pair cloned How can this be fixed? x y Pair Triple clone class Pair implements Cloneable int x; int y; //override the clone method public Object clone() throws CloneNotS upportedexception Object cloned = super.clone(); //automatically copies fields return cloned; class Triple extends Pair int z; Pair ; public class PairTest public static void main(string[] args) throws CloneNotSupportedException t.x = ; t.y = ; t.z = 3; S ystem.out.println( cloned instanceof Triple); //? S ystem.out.println( cloned instanceof Pair); //? Triple t = (Triple) cloned; S ystem.out.println( t == t); S ystem.out.println(t.x+","+t.y+","+t.z); //output: true true false,, 3
2 Cloning: so far so good! super.clone() t cloned Pair 3 3 super.clone Triple null null We get the right object. Are all of our problems solved? protected Object clone() throws CloneNotSupportedException Creates and returns a copy of this object. The precise meaning of "copy" may depend on the class of the object. For any object x, the expression: x.clone()!= x will be true, and the expression: x.clone().getclass() == x.getclass() will also be true super.clone() It is typically the case that: x.clone().equals(x) will be true By convention, the returned object should be obtained by calling super.clone. If a class and all of its superclasses (except Object) obey this convention, it will be the case that x.clone().getclass() == x.getclass(). Cloneable interface When a class implements the Cloneable, it tells Object.clone() method that it is legal for that method to make a field-for-field copy of instances of that class. Invoking Object's clone method on an instance that does not implement the Cloneable interface results in the exception CloneNotSupportedException being thrown. Cloneable interface By convention, classes that implement Cloneable interface should override Object.clone This interface does not contain the clone method. Therefore, it is not possible to clone an object merely by virtue of the fact that it implements this interface. Cloneable interface The class Object does not itself implement the interface Cloneable, Hence calling the clone method on an object whose class is Object will result in throwing an exception at run time.
3 But super.clone is Shallow Shallow Cloning class Pair implements Cloneable int x; int y; //override the clone method public Object clone() throws CloneNotS upportedexception Object cloned = super.clone(); return cloned; class Triple extends Pair int z; Pair ; public Triple() = new Pair();.x = ;.y = ; public class PairTest public static void main(string[] args) throws CloneNotSupportedException t.x = ; t.y = ; t.z = 3; S ystem.out.println(((triple) cloned). == ((Triple) t).); Triple t = (Triple) cloned; t..x = 5; t..y = 6; t.z = ; S ystem.out.println(t..x+","+t..y+","+t.z); //output is true 5, 6, 3 t t.x = ; t.y = ; t.z = 3; t 3 cloned 3 t Shallow Cloning t.x = ; t.y = ; t.z = 3; t..x = 5; t..y = 6; t.z = ; t cloned 3 Deep Cloning: Override c lone in Triple class Pair implements Cloneable int x; int y; public Object clone() throws CloneNotSupportedException Object cloned = super.clone(); return cloned; class Triple extends Pair implements Cloneable int z; Pair ; public Triple() = new Pair();.x = ;.y = ; public Object clone() throws CloneNotS upportedexception Object cloned = super.clone(); ((Triple) cloned). = (Pair).clone(); return cloned; public class PairTest public static void main(string[] args) throws CloneNotSupportedException t.x = ; t.y = ; t.z = 3; S ystem.out.println(((triple) cloned). == ((Triple) t).); Triple t = (Triple) cloned; t..x = 5; t..y = 6; t.z = ; S ystem.out.println(t..x+","+t..y+","+t.z); //output is false,, 3 Deep Cloning Collec tion t t.x = ; t.y = ; t.z = 3; t..x = 5; t..y = 6; t.z = ; t cloned 3 When writing programs we often need to work with a group of objects. Examples Concordance: collection of words with their immediate context Phonebook: collection of names with phone numbers Inventory: collection of merchandise and many more.. 3
4 Collec tion S ometimes different types of objects Collec tion S ometimes similar types of objects Operations on Collec tion add, remove, size, get, traverse ArrayLis t Recall material! "" # $"% & //traverse for (int i = ; i < coins.size(); i++) Coin c = (Coin)coins.get(i); do some thing with c Adding/Removing Elements overwrite an existing value coins.set(4, anickel); add a new value before the index add(i, c) remove removes an element at an index 4
5 Storing Numbers in an Array List Array lists store objects Use wrapper classes to store numbers '%(" )) '%("*++, %(" %)) ))%("-"% )) %)) '%("%("-"% Also have. and /" wrappers Construct array: %(" Arrays Store in variable of type double[] %(" %(" Arrays Arrays have fixe d le ngth Arrays have element of specific type, not!( Use [] to access element: 3 *++, Get array length as "4. (Not a method!) Copying Arrays Copying an array reference yields a second reference to the same array %(" %(" "" %(" ) Use " to make true copy %(" ) %("" Copying Array Elements S ystem.arraycopy(from, froms tart, to, tos tart, count); 5
6 Adding/Removing Array Elements Add an element: 5) ) 6 "4 & & # Remove an element: 5) ) 6 "4 & & Partially Filled Arrays Partially Filled Arrays Array length = maximum number of elements in array Usually, array is partially filled Need companion variable to keep track of current size Uniform naming convention: final int DATA_LENGTH = ; double[] data = new double[data_length]; int datasize = ; Update datasize as array is filled: data[datasize] = x; datasize++; Partially Filled Arrays Remember to stop at 5 when looking at array elements: % % 6 Be careful not to overfill the array 5 9 "4 8 85%)"5&& %"" Be careful to grow the array when needed: %(" ' %("* : "4 5) ' "4 ' Growing an Array 6
7 Cos t of Operations Computer programs use computer resources in order to carry out their tasks Two important resources: CPU Memory (primary storage) Other resources include secondary storage, printers, bus bandwidth, etc. Cos t of Operations We are mainly interested in CPU usage (running time) and memory usage of a program. Why should we be concerned with these? If your program is too slow or uses too much memory, then nobody will use it. Cos t of Operations Two methods for searching for a phone number in a telephone book: Linear search: start from the first page; flip through every page and compare every name with the key until found Binary search: open the book in the middle; compare key with the name in the middle; if key is smaller then do a binary search on first half; otherwise do a binary search on second half Cos t of Operations Assume the telephone book contains,, entries. How many lookups does each take: Linear search:,, lookups Binary search: each iteration cuts the number of names by a factor of until one is left. Hence, if we do this x times, then we seek x so that,,/ x is roughly. This makes x to be about = log (,,) Time Complexity Even though both algorithms achieve the same results; one uses much more resources than the other one. In general we express the running time of a program as a function of its input size: n Time complexity of sorting n integers Time complexity of searching for a word in a dictionary As n grows so does the running time Cos t of Operations Note that you cannot do a binary search on a collection whose entries are not sorted Also regardless of whether entries are sorted or not, you cannot do binary search on a collection of items which only allows sequential access (e.g. linked list) 7
8 Random Access Cost of access is independent of location; Get content of cell 6 Sequential Access Cost depends on location. Get the object after/before the lion or a given position Time Complexity We say a program takes f(n) operations (basic operations like add, subtract multiply, assign) to perform its task S ome examples f(n) =,, n f(n) = n + n + f(n) = n log(n) Time and Spac e Complexity Big O notation. A function f(n) is O(g(n)) (f is of order g) iff there exists two positive constants c and n such that f(n) < c g(n) For all n >= n Big-O Notation A function f(n) is said to be Big-O of g(n), written f(n) O(g(n)) c g(n) f(n) Implementing Collec tions S upported operations: Creation add(object) - add at the end of the list remove(index) - remove object at index size() - get the size of the list get(index) - get the object at index n n 8
9 Implementing Collec tions We can realize collections using different underlying structures: arrays linked lists trees hash tables We will investigate arrays and linked for now MyArrayList: A wrapper for an array public class MyArrayList private Object[] objs; private int last; public MyArrayList(int max) objs = new Object[max]; last = ; public void add(object o) objs[last++] = o; public void remove(int index) for(int i=index;i<last-;i++) objs[i] = objs[i+]; last--; public Object get(int index) return objs[index]; public int size() return last; Best, worst, average remove element given index i Best case: i == last Worst case: i == Average case: size (cost of removing i)/size i = the amount of work is proportional to (n + (n -) )/ n = n(n + ) / (n) = (n+)/ Best, worst, average Best case performance Often easy to compute (quickest way through the code). Worst case performance Again usually easy to compute (slowest path through the code). Average case performance Can be difficult to define average input. Back to MyArrayList Analysis often focuses on the worst case Does this make sense? Performance requirements often ask for running time better than x Analysis of MyArrayList Add is ; Very cheap Remove is : worst case Cos t of operations Add/get/size - seem very efficient Independent of the size of collection Remove - possibly move up to n elements to remove the item at element index How can we categorize the cost of different operations? 9
10 Sample s - not proportional to n (constant time) Accessing an element of an array - proportional to the size of the problem S earching through a list (remove operation) O(n ) - quadratic in n S etting elements in a matrix O(log n) - order log n S earching an ordered list via binary search O(n log n) - order n log n S orting a list (efficiently) O( n ) - exponential Sample s Problem is intractable for reasonably large problems. Many interesting problems are O( n ) (or worse) 5 9 Traveling S alesman problem Simple c omputations n 3 + n is O(n 3 ) 5n 3 + n is O( n ) n logn + n is O(n ) Comparis on of func tions Let n = 6 and assume every operation takes -8 seconds f(n) = n time = 6* -8 seconds f(n) = n time = 36* -6 seconds f(n) = n 3 time = 6* -5 seconds f(n) = n 4 time.3 seconds f(n) = n 5 time.3 minutes f(n) = n time 37 years As ymptotic Analys is Given a problem, how do you compute? Decide what the unit cost is Array access, comparison, numerical operation, Only concerned with performance for large n (n >= n ) Find the dominant term log n, n, nlog n, n, n 3,.. n How do we make ArrayList grow? public MyArrayList(int max) objs = new Object[max]; last = ; this.max = max; public void add(object o) objs[last++] = o; if(last == objs.length) Object[] temp = new Object[objs.length + max]; for(int i=;i<objs.length;i++) temp[i] = objs[i]; objs = temp;
11 Performanc e of MyArrayLis t Add is now (potentially) quite expensive Add is Remove is Get is S et(index, o) is MyArrayList vs. ArrayList Now quite similar Many more methods in ArrayList, but their implementations are quite straightforward Will write one more here indexof(object o) public int indexof(object o) for(int i=;i<last;i++) if(objs[i].equals(o)) return i; return -; boolean equals(objec t o) if(o == null) return false; return o == this Define it more intelligently for your classes. Can we improve on MyArrayLis t? S uppose instead of using an array to hold the collection, we use something else (like a linked list) Implement add, remove, get, set, indexof Obvious linked lis t implementation S ingly linked list (much like the example we did before). Two classes, a node class (MyNode) A linkedlist class (MyLinkedList) public class MyNode private Object o; private MyNode next; public MyNode(Object o) this.o = o; this.next = null; public Object geto() return o; public void seto(object o) this.o = o; public void setnext(mynode next) this.next = next; public MyNode getnext() return next;
12 public class MyLinkedList private MyNode head; public MyLinkedList() head = null; public void add(object o) MyNode tmp = new MyNode(o); MyNode pre = null; for(mynode cur=head; cur!= null; pre=cur, cur=cur.getnext()) ; if(pre == null) head = tmp; else pre.setnext(tmp); public int indexof(object o) int i = ; for(mynode cur=head; cur!= null; cur=cur.getnext(), i++) if(cur.geto().equals(o)) return i; return -; public void remove(int index) MyNode pre = null; MyNode cur = head; for(int i=;i<index;i++) pre = cur; cur = cur.getnext(); if(pre == null) head = head.getnext(); else pre.setnext(cur.getnext()); public Object get(int index) MyNode cur=head; for(int i=;i<index;i++) cur = cur.getnext(); return cur.geto(); public int size() int last = ; for(mynode cur=head; cur!= null; cur=cur.getnext(), last++); ; return last; public void set(int index, Object o) MyNode cur=head; for(int i=;i<index;i++) cur = cur.getnext(); cur.seto(o); So how did we do? Can we improve things? Create add remove get MyArrayList MyLinkedList One quick improvement Maintain the length of the list in the class S et to initially Increment by in add Decrement by in delete Return its value in size set indexof size
13 Revised version But can we do better? Create add remove MyArrayList MyLinkedList remove, get set and indexof require search Unlikely that we can improve on these with the current data structure Can we improve on add? get set indexof size Add spends all of its effort finding the end of the list. Can we maintain a last node? Add, remove will need some work public class MyLinkedList private MyNode head, tail; public MyLinkedList() head = null; tail = null; public void add(object o) MyNode tmp = new MyNode(o); if(head == null) head = tmp; tail = tmp; else tail.setnext(tmp); tail = tmp; public void remove(int index) MyNode pre = null; MyNode cur = head; for(int i=;i<index;i++) pre = cur; cur = cur.getnext(); if(pre == null) head = head.getnext(); if(head == null) tail = null; else pre.setnext(cur.getnext()); if(cur.getnext() == null) tail = pre; Revised version So how bad is this Create add remove get set indexof MyArrayList MyLinkedList S uppose all VIS A card numbers (5 digits) are in a list ( 5 numbers) S uppose each unit operation can be done in -7 seconds. Then it will only take on the order of 8 seconds to search list (3 years). For big problems, is not good enough size 3
14 But for small problems ArrayList Vector (use ArrayList instead) LinkedList Great for S tack and Queue implementations (more on these later) What makes lists? Being able to access arbitrary elements. If we limit access to the list, can we enhance performance? Two classic alternatives Limit add to one end of the list Limit remove to one end of the list LIFO (stack) FIFO (queue) Create Stack Push - add an element to the top of the stack Pop - remove the top element of the stack isempty - check if the stack is empty Create Queue Enqueue - add to the end of the queue Dequeue - remote top element from the queue isempty - check to see if the queue is empty Two-Dimens ional Arrays Matrix with rows and columns Example: Tic Tac Toe board char[][] board = new char[3][3]; board[i][j] = 'x'; File Tic Tac Toe.java /** A 3 x 3 Tic-Tac-Toe board. 3 */ 4 public class TicTacToe 5 6 /** 7 Constructs an empty board. 8 */ 9 public TicTacToe() board = new char[rows ][COLUMNS ]; 3 //fill with spaces 4 for (int i = ; i < ROWS ; i++) 5 for (int j = ; j < COLUMNS ; j++) 6 board[i][j] = ''; 7 4
15 8 9 /** Sets a field in the board. The field must be param i the row param j the column index param player the player ('x'or 'o') 4 */ 5 public void set(int i, int j, char player) 6 7 if (board[i][j]!= '') 8 throw new IllegalArgumentException("Position occupied"); 9 board[i][j] = player; /** 33 Creates a string representation of the board such as 34 x o 35 x 36 o return the string representation 38 public S tring tos tring() 39 4 S tring r = ""; 4 for (int i = ; i < ROWS ; i++) 4 43 r = r + " "; 44 for (int j = ; j < COLUMNS ; j++) 45 r = r + board[i][j]; 46 r = r + " \n"; return r; private char[][] board; 5 private static final int ROWS = 3; 53 private static final int COLUMNS = 3; 54 File Tic Tac ToeTes t.java import javax.swing.j OptionPane; 3 /** 4 This program tests the TicTacToe class by prompting the 5 user to set positions on the board and printing out the 6 result. 7 */ 8 public class TicTacToeTest 9 public static void main(string[] args) char player = 'x'; 3 TicTacToe game = new TicTacToe(); 4 while (true) 5 6 System.out.println(game); //calls game.tostring() 7 String input = JOptionPane.showInputDialog( 8 "Row for " + player + " (Cancel to exit)"); 9 if (input == null) System.exit(); int row = Integer.parseInt(input); input = J OptionPane.showInputDialog( "Column for " + player); 3 int column = Integer.parseInt(input); 4 game.set(row, column, player); 5 if (player == 'x') player = 'o'; else player = 'x'; Read chapter 3 This week Prepare for midterm this week 7:-9: No aids (no calculators, cheat sheets, etc) S ome multiple choice questions, some short answer questions, and a larger question Arrays, array lists, big O notation 5
Outline. runtime of programs algorithm efficiency Big-O notation List interface Array lists
Outline runtime of programs algorithm efficiency Big-O notation List interface Array lists Runtime of Programs compare the following two program fragments: int result = 1; int result = 1; for (int i=2;
More informationTecniche di Progettazione: Design Patterns
Tecniche di Progettazione: Design Patterns GoF: Memento Prototype Visitor 1 Design patterns, Laura Semini, Università di Pisa, Dipartimento di Informatica. Memento 2 Design patterns, Laura Semini, Università
More informationCOSC This week. List ADT. Abstract Data Type (ADT) Lis t ADT Implementations. Data Struc tures and Algorithms
This week COSC 1030.03 Week 9, March 8, 2004 Read chapter 19 Work on assignment #3 Discussed in Tutorial this week Must have a partial solution shown to your TA next week. Data structures (continued) S
More informationArrays and Array Lists
Arrays and Array Lists Advanced Programming ICOM 4015 Lecture 7 Reading: Java Concepts Chapter 8 Fall 2006 Slides adapted from Java Concepts companion slides 1 Lecture Goals To become familiar with using
More informationChapter 8. Arrays and Array Lists. Chapter Goals. Chapter Goals. Arrays. Arrays. Arrays
Chapter 8 Arrays and Array Lists Chapter Goals To become familiar with using arrays and array lists To learn about wrapper classes, auto-boxing and the generalized for loop To study common array algorithms
More informationList ADT. Announcements. The List interface. Implementing the List ADT
Announcements Tutoring schedule revised Today s topic: ArrayList implementation Reading: Section 7.2 Break around 11:45am List ADT A list is defined as a finite ordered sequence of data items known as
More informationArrays. https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
1 Arrays Arrays in Java an array is a container object that holds a fixed number of values of a single type the length of an array is established when the array is created 2 https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
More informationImplementing a List in Java. CSE 143 Java. Just an Illusion? List Interface (review) Using an Array to Implement a List.
Implementing a List in Java CSE 143 Java List Implementation Using Arrays Reading: Ch. 13 Two implementation approaches are most commonly used for simple lists: Arrays Linked list Java Interface List concrete
More informationArrays and ArrayLists. Ananda Gunawardena
Arrays and ArrayLists Ananda Gunawardena Introduction Array is a useful and powerful aggregate data structure presence in modern programming languages Arrays allow us to store arbitrary sized sequences
More informationComputer Science 9608 (Notes) Chapter: 4.1 Computational thinking and problem-solving
In Computer Science, an abstract data type (ADT) is a mathematical model for a certain data type or structures. This doesn t mean that the ADTs cannot be programmed. But that we must first understand them
More informationQuestion 1 [20 points]
Question 1 [20 points] a) Write the following mathematical expression in Java. c=math.sqrt(math.pow(a,2)+math.pow(b,2)- 2*a*b*Math.cos(gamma)); b) Write the following Java expression in mathematical notation.
More informationChapter Seven: Arrays and Array Lists. Chapter Goals
Chapter Seven: Arrays and Array Lists Chapter Goals To become familiar with using arrays and array lists To learn about wrapper classes, auto-boxing and the generalized for loop To study common array algorithms
More informationRecursion (Part 3) 1
1 Recursion (Part 3) Computational complexity computational complexity is concerned with describing the amount of resources needed to run an algorithm for our purposes, the resource is time complexity
More informationSummer Final Exam Review Session August 5, 2009
15-111 Summer 2 2009 Final Exam Review Session August 5, 2009 Exam Notes The exam is from 10:30 to 1:30 PM in Wean Hall 5419A. The exam will be primarily conceptual. The major emphasis is on understanding
More informationCS/CE 2336 Computer Science II
CS/CE 2336 Computer Science II UT D Session 11 OO Data Structures Lists, Stacks, Queues Adapted from D. Liang s Introduction to Java Programming, 8 th Ed. 2 What is a Data Structure? A collection of data
More informationCOMP200 GENERICS. OOP using Java, from slides by Shayan Javed
1 1 COMP200 GENERICS OOP using Java, from slides by Shayan Javed 2 ArrayList and Java Generics 3 Collection A container object that groups multiple objects 4 Collection A container object that groups multiple
More informationAn Introduction to Data Structures
An Introduction to Data Structures Advanced Programming ICOM 4015 Lecture 17 Reading: Java Concepts Chapter 20 Fall 2006 Adapded from Java Concepts Companion Slides 1 Chapter Goals To learn how to use
More informationASYMPTOTIC COMPLEXITY
Simplicity is a great virtue but it requires hard work to achieve it and education to appreciate it. And to make matters worse: complexity sells better. - Edsger Dijkstra ASYMPTOTIC COMPLEXITY Lecture
More informationCS/ENGRD 2110 Object-Oriented Programming and Data Structures Spring 2012 Thorsten Joachims. Lecture 10: Asymptotic Complexity and
CS/ENGRD 2110 Object-Oriented Programming and Data Structures Spring 2012 Thorsten Joachims Lecture 10: Asymptotic Complexity and What Makes a Good Algorithm? Suppose you have two possible algorithms or
More informationTecniche di Progettazione: Design Patterns
Tecniche di Progettazione: Design Patterns GoF: Prototype 1 Design patterns, Laura Semini, Università di Pisa, Dipartimento di Informatica. Prototype Pattern A creational pattern Specify the kinds of objects
More informationReview. CSE 143 Java. A Magical Strategy. Hash Function Example. Want to implement Sets of objects Want fast contains( ), add( )
Review CSE 143 Java Hashing Want to implement Sets of objects Want fast contains( ), add( ) One strategy: a sorted list OK contains( ): use binary search Slow add( ): have to maintain list in sorted order
More informationCH ALGORITHM ANALYSIS CH6. STACKS, QUEUES, AND DEQUES
CH4.2-4.3. ALGORITHM ANALYSIS CH6. STACKS, QUEUES, AND DEQUES ACKNOWLEDGEMENT: THESE SLIDES ARE ADAPTED FROM SLIDES PROVIDED WITH DATA STRUCTURES AND ALGORITHMS IN JAVA, GOODRICH, TAMASSIA AND GOLDWASSER
More informationMeasuring algorithm efficiency
CMPT 225 Measuring algorithm efficiency Timing Counting Cost functions Cases Best case Average case Worst case Searching Sorting O Notation O notation's mathematical basis O notation classes and notations
More informationImplementing a List in Java. CSE 143 Java. List Interface (review) Just an Illusion? Using an Array to Implement a List.
Implementing a List in Java CSE 143 Java List Implementation Using Arrays Reading: Ch. 22 Two implementation approaches are most commonly used for simple lists: Arrays Linked list Java Interface List concrete
More informationDepartment of Computer Science and Engineering. CSE 2011: Fundamentals of Data Structures Winter 2009, Section Z
Department of omputer Science and Engineering SE 2011: Fundamentals of Data Structures Winter 2009, Section Z Instructor: N. Vlajic Date: pril 14, 2009 Midterm Examination Instructions: Examination time:
More informationSelection, Bubble, Insertion, Merge, Heap, Quick Bucket, Radix
Spring 2010 Review Topics Big O Notation Heaps Sorting Selection, Bubble, Insertion, Merge, Heap, Quick Bucket, Radix Hashtables Tree Balancing: AVL trees and DSW algorithm Graphs: Basic terminology and
More informationModule 1: Asymptotic Time Complexity and Intro to Abstract Data Types
Module 1: Asymptotic Time Complexity and Intro to Abstract Data Types Dr. Natarajan Meghanathan Professor of Computer Science Jackson State University Jackson, MS 39217 E-mail: natarajan.meghanathan@jsums.edu
More informationCS201 ArrayLists, Generics, and Dynamic Data Structures (Chapters 14, 15)
CS201 ArrayLists, Generics, and Dynamic Data Structures (Chapters 14, 15) A data structure is a software construct used to organize our data in a particular way. Some common data structures include lists,
More informationImplementing Lists, Stacks, Queues, and Priority Queues
Implementing Lists, Stacks, Queues, and Priority Queues CSE260, Computer Science B: Honors Stony Brook University http://www.cs.stonybrook.edu/~cse260 1 Objectives To design common features of lists in
More informationStandard ADTs. Lecture 19 CS2110 Summer 2009
Standard ADTs Lecture 19 CS2110 Summer 2009 Past Java Collections Framework How to use a few interfaces and implementations of abstract data types: Collection List Set Iterator Comparable Comparator 2
More informationAlgorithm Efficiency and Big-O
+ Algorithm Efficiency and More List implementations + Algorithm Efficiency and Big-O Section 2.4 1 + Algorithm Efficiency and Big-O n Getting a precise measure of the performance of an algorithm is difficult
More informationRecitation 9. Prelim Review
Recitation 9 Prelim Review 1 Heaps 2 Review: Binary heap min heap 1 2 99 4 3 PriorityQueue Maintains max or min of collection (no duplicates) Follows heap order invariant at every level Always balanced!
More informationAlgorithmic Analysis. Go go Big O(h)!
Algorithmic Analysis Go go Big O(h)! 1 Corresponding Book Sections Pearson: Chapter 6, Sections 1-3 Data Structures: 4.1-4.2.5 2 What is an Algorithm? Informally, any well defined computational procedure
More informationComputer Science 62. Bruce/Mawhorter Fall 16. Midterm Examination. October 5, Question Points Score TOTAL 52 SOLUTIONS. Your name (Please print)
Computer Science 62 Bruce/Mawhorter Fall 16 Midterm Examination October 5, 2016 Question Points Score 1 15 2 10 3 10 4 8 5 9 TOTAL 52 SOLUTIONS Your name (Please print) 1. Suppose you are given a singly-linked
More informationArrays. Chapter Arrays What is an Array?
Chapter 8 Arrays 81 Arrays 811 What is an Array? To motivate why we might be interested in using arrays, let us implement an app that creates a collection of doubles We will keep track of the number of
More informationCSC 321: Data Structures. Fall 2013
CSC 321: Data Structures Fall 2013 Lists, stacks & queues Collection classes: List (ArrayList, LinkedList), Set (TreeSet, HashSet), Map (TreeMap, HashMap) ArrayList performance and implementation LinkedList
More informationCSC 222: Object-Oriented Programming Spring 2012
CSC 222: Object-Oriented Programming Spring 2012 Searching and sorting sequential search algorithm analysis: big-oh, rate-of-growth binary search insertion sort, selection sort 1 Searching a list suppose
More informationBasic Data Structures
Basic Data Structures Some Java Preliminaries Generics (aka parametrized types) is a Java mechanism that enables the implementation of collection ADTs that can store any type of data Stack s1
More informationAlgorithm Analysis. Performance Factors
Algorithm Analysis How can we demonstrate that one algorithm is superior to another without being misled by any of the following problems: Special cases Every algorithm has certain inputs that allow it
More informationBasic Data Structures 1 / 24
Basic Data Structures 1 / 24 Outline 1 Some Java Preliminaries 2 Linked Lists 3 Bags 4 Queues 5 Stacks 6 Performance Characteristics 2 / 24 Some Java Preliminaries Generics (aka parametrized types) is
More informationAnalysis of Algorithms. CS 1037a Topic 13
Analysis of Algorithms CS 1037a Topic 13 Overview Time complexity - exact count of operations T(n) as a function of input size n - complexity analysis using O(...) bounds - constant time, linear, logarithmic,
More informationCS 307 Midterm 2 Fall 2008
Points off 1 2 3 4 5 Total off Net Score Exam Number: CS 307 Midterm 2 Fall 2008 Name UTEID login name TA's Name: Mikie Ron Sarah (Circle One) Instructions: 1. Please turn off your cell phones and other
More informationCS 216 Exam 1 Fall SOLUTION
CS 216 Exam 1 Fall 2004 - SOLUTION Name: Lab Section: Email Address: Student ID # This exam is closed note, closed book. You will have an hour and fifty minutes total to complete the exam. You may NOT
More informationInsertions and removals follow the Fist-In First-Out rule: Insertions: at the rear of the queue Removals: at the front of the queue
Queues CSE 2011 Fall 2009 9/28/2009 7:56 AM 1 Queues: FIFO Insertions and removals follow the Fist-In First-Out rule: Insertions: at the rear of the queue Removals: at the front of the queue Applications,
More informationWhat did we talk about last time? Finished hunters and prey Class variables Constants Class constants Started Big Oh notation
Week 12 - Friday What did we talk about last time? Finished hunters and prey Class variables Constants Class constants Started Big Oh notation Here is some code that sorts an array in ascending order
More informationCS 307 Final Spring 2009
Points off 1 2 3 4 5 Total off Net Score CS 307 Final Spring 2009 Name UTEID login name Instructions: 1. Please turn off your cell phones. 2. There are 5 questions on this test. 3. You have 3 hours to
More informationASYMPTOTIC COMPLEXITY
Simplicity is a great virtue but it requires hard work to achieve it and education to appreciate it. And to make matters worse: complexity sells better. - Edsger Dijkstra ASYMPTOTIC COMPLEXITY Lecture
More informationList ADT. B/W Confirming Pages
wu3399_ch8.qxd //7 :37 Page 98 8 List ADT O b j e c t i v e s After you have read and studied this chapter, you should be able to Describe the key features of the List ADT. the List ADT using an array
More informationCSC 321: Data Structures. Fall 2012
CSC 321: Data Structures Fall 2012 Lists, stacks & queues Collection classes: List (ArrayList, LinkedList), Set (TreeSet, HashSet), Map (TreeMap, HashMap) ArrayList performance and implementation LinkedList
More informationInterfaces & Generics
Interfaces & Generics CSC207 Winter 2018 The Programming Interface The "user" for almost all code is a programmer. That user wants to know:... what kinds of object your class represents... what actions
More informationCS 221 Review. Mason Vail
CS 221 Review Mason Vail Inheritance (1) Every class - except the Object class - directly inherits from one parent class. Object is the only class with no parent. If a class does not declare a parent using
More informationDUKE UNIVERSITY Department of Computer Science. Test 1: CompSci 100
DUKE UNIVERSITY Department of Computer Science Test 1: CompSci 100 Name (print): Community Standard acknowledgment (signature): Problem 1 value 9 pts. grade Problem 2 9 pts. Problem 3 6 pts. Problem 4
More informationCsci 102: Sample Exam
Csci 102: Sample Exam Duration: 65 minutes Name: NetID: Student to your left: Student to your right: DO NOT OPEN THIS EXAM UNTIL INSTRUCTED Instructions: Write your full name and your NetID on the front
More informationCSE 373 Spring Midterm. Friday April 21st
CSE 373 Spring 2006 Data Structures and Algorithms Midterm Friday April 21st NAME : Do all your work on these pages. Do not add any pages. Use back pages if necessary. Show your work to get partial credit.
More informationOverview of Data. 1. Array 2. Linked List 3. Stack 4. Queue
Overview of Data A data structure is a particular way of organizing data in a computer so that it can be used effectively. The idea is to reduce the space and time complexities of different tasks. Below
More informationData Structures Question Bank Multiple Choice
Section 1. Fundamentals: Complexity, Algorthm Analysis 1. An algorithm solves A single problem or function Multiple problems or functions Has a single programming language implementation 2. A solution
More informationAbstract Data Types (ADTs) Queues & Priority Queues. Sets. Dictionaries. Stacks 6/15/2011
CS/ENGRD 110 Object-Oriented Programming and Data Structures Spring 011 Thorsten Joachims Lecture 16: Standard ADTs Abstract Data Types (ADTs) A method for achieving abstraction for data structures and
More informationLecture Notes. char myarray [ ] = {0, 0, 0, 0, 0 } ; The memory diagram associated with the array can be drawn like this
Lecture Notes Array Review An array in C++ is a contiguous block of memory. Since a char is 1 byte, then an array of 5 chars is 5 bytes. For example, if you execute the following C++ code you will allocate
More informationKeeping Order:! Stacks, Queues, & Deques. Travis W. Peters Dartmouth College - CS 10
Keeping Order:! Stacks, Queues, & Deques 1 Stacks 2 Stacks A stack is a last in, first out (LIFO) data structure Primary Operations: push() add item to top pop() return the top item and remove it peek()
More informationJava Array List Interview Questions
Java Array List Interview Questions codespaghetti.com/arraylist-interview-questions/ Array List Java Array List Interview Questions, Algorithms and Array List Programs. Table of Contents: CHAPTER 1: Top
More informationDEEPIKA KAMBOJ UNIT 2. What is Stack?
What is Stack? UNIT 2 Stack is an important data structure which stores its elements in an ordered manner. You must have seen a pile of plates where one plate is placed on top of another. Now, when you
More informationWYSE Academic Challenge State Finals Computer Science 2007 Solution Set
WYSE Academic Challenge State Finals Computer Science 2007 Solution Set 1. Correct answer: C. a) PGP is for encrypting documents, traditionally used for email. b) SSH is used to gain secure access to a
More informationWeek 6. Data structures
1 2 3 4 5 n Week 6 Data structures 6 7 n 8 General remarks We start considering Part III Data Structures from CLRS. As a first example we consider two special of buffers, namely stacks and queues. Reading
More informationcsci 210: Data Structures Stacks and Queues
csci 210: Data Structures Stacks and Queues 1 Summary Topics Stacks and Queues as abstract data types ( ADT) Implementations arrays linked lists Analysis and comparison Applications: searching with stacks
More informationComputer Science 62. Midterm Examination
Computer Science 62 Bruce/Mawhorter Fall 16 Midterm Examination October 5, 2016 Question Points Score 1 15 2 10 3 10 4 8 5 9 TOTAL 52 Your name (Please print) 1. Suppose you are given a singly-linked list
More informationWe've tried to include the common errors and grading standard for every question.
Fall 2003 CS61B Midterm (50/300 points) ;;;; Meta ;;;; GS = Grading Standard We've tried to include the common errors and grading standard for every question. QUESTION 1 GS: The T/F questions were worth
More informationCSL 201 Data Structures Mid-Semester Exam minutes
CL 201 Data tructures Mid-emester Exam - 120 minutes Name: Roll Number: Please read the following instructions carefully This is a closed book, closed notes exam. Calculators are allowed. However laptops
More informationComplexity, General. Standard approach: count the number of primitive operations executed.
Complexity, General Allmänt Find a function T(n), which behaves as the time it takes to execute the program for input of size n. Standard approach: count the number of primitive operations executed. Standard
More information4.1 COMPUTATIONAL THINKING AND PROBLEM-SOLVING
4.1 COMPUTATIONAL THINKING AND PROBLEM-SOLVING 4.1.2 ALGORITHMS ALGORITHM An Algorithm is a procedure or formula for solving a problem. It is a step-by-step set of operations to be performed. It is almost
More informationEXAMINATIONS 2015 COMP103 INTRODUCTION TO DATA STRUCTURES AND ALGORITHMS
T E W H A R E W Ā N A N G A O T E Student ID:....................... Ū P O K O O T E I K A A M Ā U I VUW VICTORIA U N I V E R S I T Y O F W E L L I N G T O N EXAMINATIONS 2015 TRIMESTER 2 COMP103 INTRODUCTION
More informationThe Java Collections Framework and Lists in Java Parts 1 & 2
The Java Collections Framework and Lists in Java Parts 1 & 2 Chapter 9 Chapter 6 (6.1-6.2.2) CS 2334 University of Oklahoma Brian F. Veale Groups of Data Data are very important to Software Engineering
More informationFaculty of Science FINAL EXAMINATION COMP-250 A Introduction to Computer Science School of Computer Science, McGill University
NAME: STUDENT NUMBER:. Faculty of Science FINAL EXAMINATION COMP-250 A Introduction to Computer Science School of Computer Science, McGill University Examimer: Prof. Mathieu Blanchette December 8 th 2005,
More informationContainers and genericity. A standardized naming scheme. Cursor properties. Lists. Adding a cell. A specific implementation: (singly) linked lists
Topics for this lecture Chair of Software Engineering Einführung in die Programmierung Introduction to Programming Containers and genericity Container operations Prof. Dr. Bertrand Meyer Lists October
More informationGeneric classes & the Java Collections Framework. *Really* Reusable Code
Generic classes & the Java Collections Framework *Really* Reusable Code First, a bit of history Since Java version 5.0, Java has borrowed a page from C++ and offers a template mechanism, allowing programmers
More informationQueues Fall 2018 Margaret Reid-Miller
Queues 15-121 Fall 2018 Margaret Reid-Miller Today Exam 2 is next Tuesday, October 30 Writing methods various classes that implement Lists. Methods using Lists and Big-O w/ ArrayList or LinkedLists Prove
More informationCS171 Midterm Exam. October 29, Name:
CS171 Midterm Exam October 29, 2012 Name: You are to honor the Emory Honor Code. This is a closed-book and closed-notes exam. You have 50 minutes to complete this exam. Read each problem carefully, and
More informationRevision Statement while return growth rate asymptotic notation complexity Compare algorithms Linear search Binary search Preconditions: sorted,
[1] Big-O Analysis AVERAGE(n) 1. sum 0 2. i 0. while i < n 4. number input_number(). sum sum + number 6. i i + 1 7. mean sum / n 8. return mean Revision Statement no. of times executed 1 1 2 1 n+1 4 n
More informationCSC 1351: Final. The code compiles, but when it runs it throws a ArrayIndexOutOfBoundsException
VERSION A CSC 1351: Final Name: 1 Interfaces, Classes and Inheritance 2 Basic Data Types (arrays, lists, stacks, queues, trees,...) 2.1 Does the following code compile? If it does not, how can it be fixed?
More informationSum this up for me. Let s write a method to calculate the sum from 1 to some n. Gauss also has a way of solving this. Which one is more efficient?
Sum this up for me Let s write a method to calculate the sum from 1 to some n public static int sum1(int n) { int sum = 0; for (int i = 1; i
More informationCSC 222: Object-Oriented Programming. Fall 2015
CSC 222: Object-Oriented Programming Fall 2015 Searching and sorting sequential search vs. binary search algorithm analysis: big-oh, rate-of-growth O(N 2 ) sorts: insertion sort, selection sort 1 Searching
More informationCMP Points Total Midterm Spring Version (16 Points) Multiple Choice:
CMP-338 106 Points Total Midterm Spring 2017 Version 1 Instructions Write your name and version number on the top of the yellow paper. Answer all questions on the yellow paper. One question per page. Use
More informationCS61BL Summer 2013 Midterm 2
CS61BL Summer 2013 Midterm 2 Sample Solutions + Common Mistakes Question 0: Each of the following cost you.5 on this problem: you earned some credit on a problem and did not put your five digit on the
More informationCS 314 Exam 2 Spring
Points off 1 2 3 4 5 Total off CS 314 Exam 2 Spring 2017 Your Name Your UTEID Instructions: 1. There are 5 questions on this test. 100 points available. Scores will be scaled to 200 points. 2. You have
More information1.00 Lecture 26. Data Structures: Introduction Stacks. Reading for next time: Big Java: Data Structures
1.00 Lecture 26 Data Structures: Introduction Stacks Reading for next time: Big Java: 19.1-19.3 Data Structures Set of primitives used in algorithms, simulations, operating systems, applications to: Store
More informationWhat is an algorithm?
Reminders CS 142 Lecture 3 Analysis, ADTs & Objects Program 1 was assigned - Due on 1/27 by 11:55pm 2 Abstraction Measuring Algorithm Efficiency When you utilize the mylist.index(item) function you are
More informationInterfaces, collections and comparisons
תכנות מונחה עצמים תרגול מספר 4 Interfaces, collections and comparisons Interfaces Overview Overview O Interface defines behavior. Overview O Interface defines behavior. O The interface includes: O Name
More informationCSC 172 Data Structures and Algorithms. Lecture #9 Spring 2018
CSC 172 Data Structures and Algorithms Lecture #9 Spring 2018 SINGLY LINKED LIST 3.1.3 Linked lists We will consider these for Singly linked lists Doubly linked lists Basic Singly Linked List class Node
More informationBasic Data Structures (Version 7) Name:
Prerequisite Concepts for Analysis of Algorithms Basic Data Structures (Version 7) Name: Email: Concept: mathematics notation 1. log 2 n is: Code: 21481 (A) o(log 10 n) (B) ω(log 10 n) (C) Θ(log 10 n)
More informationWhat is the Java Collections Framework?
1 of 13 What is the Java Collections Framework? To begin with, what is a collection?. I have a collection of comic books. In that collection, I have Tarzan comics, Phantom comics, Superman comics and several
More informationLinked Lists. Chapter 12.3 in Savitch
Linked Lists Chapter 12.3 in Savitch Preliminaries n Arrays are not always the optimal data structure: q An array has fixed size needs to be copied to expand its capacity q Adding in the middle of an array
More informationThe Limits of Sorting Divide-and-Conquer Comparison Sorts II
The Limits of Sorting Divide-and-Conquer Comparison Sorts II CS 311 Data Structures and Algorithms Lecture Slides Monday, October 12, 2009 Glenn G. Chappell Department of Computer Science University of
More informationCS 231 Data Structures and Algorithms Fall Algorithm Analysis Lecture 16 October 10, Prof. Zadia Codabux
CS 231 Data Structures and Algorithms Fall 2018 Algorithm Analysis Lecture 16 October 10, 2018 Prof. Zadia Codabux 1 Agenda Algorithm Analysis 2 Administrative No quiz this week 3 Algorithm Analysis 4
More informationSection 01: Solutions
Section 01: Solutions 1. CSE 143 review 1.1. Reference semantics Quick Check 2 [0, 1] 1 [0, 1] 1 [1, 2] 0 [1, 2] 0 [0, 0] 0 [1, 2] (a) What is the output of this program? public class Mystery2 { public
More informationExtended Introduction to Computer Science CS1001.py Lecture 7: Basic Algorithms: Sorting, Merge; Time Complexity and the O( ) notation
Extended Introduction to Computer Science CS1001.py Lecture 7: Basic Algorithms: Sorting, Merge; Time Complexity and the O( ) notation Instructors: Daniel Deutch, Amir Rubinstein Teaching Assistants: Michal
More informationCSE 373 Winter 2009: Midterm #1 (closed book, closed notes, NO calculators allowed)
Name: Email address: CSE 373 Winter 2009: Midterm #1 (closed book, closed notes, NO calculators allowed) Instructions: Read the directions for each question carefully before answering. We may give partial
More informationStack and Queue. Stack:
Stack and Queue Stack: Abstract Data Type A stack is a container of objects that are inserted and removed according to the last-in first-out (LIFO) principle. In the pushdown stacks only two operations
More informationCS61BL: Data Structures & Programming Methodology Summer 2014
CS61BL: Data Structures & Programming Methodology Summer 2014 Instructor: Edwin Liao Midterm 2 July 30, 2014 Name: Student ID Number: Section Time: TA: Course Login: cs61bl-?? Person on Left: Possibly
More informationCMSC 132: Object-Oriented Programming II. Stack and Queue
CMSC 132: Object-Oriented Programming II Stack and Queue 1 Stack Allows access to only the last item inserted. An item is inserted or removed from the stack from one end called the top of the stack. This
More informationGenerics. IRS W-9 Form
Generics IRS W-9 Form Generics Generic class and methods. BNF notation Syntax Non-parametrized class: < class declaration > ::= "class" < identifier > ["extends" < type >] ["implements" < type list >]
More informationUNIVERSITY OF WATERLOO DEPARTMENT OF ELECTRICAL AND COMPUTER ENGINEERING E&CE 250 ALGORITHMS AND DATA STRUCTURES
UNIVERSITY OF WATERLOO DEPARTMENT OF ELECTRICAL AND COMPUTER ENGINEERING E&CE 250 ALGORITHMS AND DATA STRUCTURES Midterm Examination Douglas Wilhelm Harder 1.5 hrs, 2005/02/17 11 pages Name (last, first):
More information