KF5008 Collections(2) Dr Nick Dalton.

Slides:



Advertisements
Similar presentations
Stacks, Queues, and Linked Lists
Advertisements

AITI Lecture 19 Linked List Adapted from MIT Course 1.00 Spring 2003 Lecture 26 and Tutorial Note 9 (Teachers: Please do not erase the above note)
0 of 37 Stacks and Queues Lecture of 37 Abstract Data Types To use a method, need to know its essentials: signature and return type o additionally,
Stacks, Queues, and Deques. 2 A stack is a last in, first out (LIFO) data structure Items are removed from a stack in the reverse order from the way they.
9-1 9 Queue ADTs Queue concepts. Queue applications. A queue ADT: requirements, contract. Implementations of queues: using arrays, linked lists. Queues.
7-1 7 Queue ADTs Queue concepts. Queue applications. A queue ADT: requirements, contract. Implementations of queues: using arrays, linked lists. Queues.
Queues Chapter 6. Chapter Objectives  To learn how to represent a waiting line (queue) and how to use the methods in the Queue interface for insertion.
CS 106 Introduction to Computer Science I 12 / 06 / 2006 Instructor: Michael Eckmann.
1 Chapter 24 Lists Stacks and Queues. 2 Objectives F To design list with interface and abstract class (§24.2). F To design and implement a dynamic list.
Unit 11 1 Unit 11: Data Structures H We explore some simple techniques for organizing and managing information H This unit focuses on: Abstract Data Types.
CSSE221: Software Dev. Honors Day 13 Announcements Announcements Contractions throughout the night… Contractions throughout the night… Late day assignments.
Queues Chapter 6. Chapter 6: Queues2 Chapter Objectives To learn how to represent a waiting line (queue) and how to use the methods in the Queue interface.
Fall 2007CS 2251 Queues Chapter 6. Fall 2007CS 2252 Chapter Objectives To learn how to represent a waiting line (queue) and how to use the methods in.
Stacks, Queues, and Deques
Stacks, Queues, and Deques
CM0551 Exam Prep. What are an algorithm’s time and space complexity? (2 marks) Answer: The growth rate of the algorithm’s time requirement and the computer.
COMP 103 Linked Lists. 2 RECAP-TODAY RECAP  Linked Structures: LinkedNode  Iterating and printing Linked Nodes  Inserting and removing Linked Nodes.
Data structures Abstract data types Java classes for Data structures and ADTs.
1 Linked-list, stack and queue. 2 Outline Abstract Data Type (ADT)‏ Linked list Stack Queue.
(c) University of Washington16-1 CSC 143 Java Linked Lists Reading: Ch. 20.
1 Stacks (Continued) and Queues Array Stack Implementation Linked Stack Implementation The java.util.Stack class Queue Abstract Data Type (ADT) Queue ADT.
List Interface and Linked List Mrs. Furman March 25, 2010.
1. What is it? It is a queue that access elements according to their importance value. Eg. A person with broken back should be treated before a person.
LINKED LISTS.
Chapter 3 Lists, Stacks, Queues. Abstract Data Types A set of items – Just items, not data types, nothing related to programming code A set of operations.
Stacks and Queues. 2 Abstract Data Types (ADTs) abstract data type (ADT): A specification of a collection of data and the operations that can be performed.
Collections ABCD ABCD Head Node Tail Node array doubly linked list Traditional Arrays and linked list: Below is memory representation of traditional.
Linked Data Structures
Linked List, Stacks Queues
Linked Lists, Queues, Stacks
Prefix notation in action
Lecture 6 of Computer Science II
Comprehensive Introduction to OOP with Java, C. Thomas Wu Stack ADT
Cpt S 122 – Data Structures Abstract Data Types
Marcus Biel, Software Craftsman
4. Linked Lists.
CS 1114: Implementing Search
CSE 116/504 – Intro. To Computer Science for Majors II
Chapter 6: The Stack Abstract Data Type
Queues Queues Queues.
Top Ten Words that Almost Rhyme with “Peas”
Introduction to Data Structures
Stacks and Queues.
Prof. Neary Adapted from slides by Dr. Katherine Gibson
structures and their relationships." - Linus Torvalds
Stacks.
Stacks, Queues, and Deques
Building Java Programs
Stacks and Queues.
Stacks, Queues, and Deques
Java Collections Framework
Building Java Programs
Building Java Programs
Linked Lists.
CS2013 Lecture 4 John Hurley Cal State LA.
Chapter 24 Implementing Lists, Stacks, Queues, and Priority Queues
Stacks and Queues CLRS, Section 10.1.
Protocols CS 4311 Wirfs Brock et al., Designing Object-Oriented Software, Prentice Hall, (Chapter 8) Meyer, B., Applying design by contract, Computer,
CS210- Lecture 5 Jun 9, 2005 Agenda Queues
Stacks.
More Data Structures (Part 1)
Priority Queues Chapters 10 & 26.
Stacks Chapter 5.
CSC 143 Java Linked Lists.
Stacks, Queues, and Deques
8 List ADTs List concepts. List applications.
TCSS 143, Autumn 2004 Lecture Notes
structures and their relationships." - Linus Torvalds
Stacks and Queues.
Presentation transcript:

KF5008 Collections(2) Dr Nick Dalton

Story so far Interfaces or Abstract Data types – say how thing should work Data Structures ( Concreate classes ) – actually do the work Different implementations have different strengths and weaknesses. Choose the right one and your program goes really fast.

Last weeks break question Who invented the communication technology behind the modern mobile phone? Last weeks break question

Hedy Lamarr 1940 The original actress/model/antifascist and inventor See Frequency-hopping spread spectrum 1930 and 1940’s Movie star Hedy Lammar patented the original technology. The sort which is in every phone. Speaking of phones we have pproblem for the week.

We have a dating app. It keeps a list of people who are near you who are you know available. But it’s really really slow and uses up battery like crazy So you get approached by these guys. They have a start up developing an App. The app has to parts a server and a android client. Both in java. When you get close to another Weeper user to updates a list of other weepers who are near you. But it’s slow.

Hands up – any ideas? Diagnosis? ArrayList<People> potentials; … void updateNew( People p ) { potentials.insert(0, p); // INSERT } Void tooFarAway( People p ) potentials.remove( p ); Sounds like the System is being inefficient but what or how? Hands up – any ideas?

From last week Insert in to an array list is slow Removing from an array is slow. This application is doing it *A LOT* so slow + Battery draining.

What do we need? We need a ArrayList which is cheap to insert ( at head ) We need an ArrayList which is cheap to remove and element. We don’t iterate over it much ( can be slow ) We don’t get an indexed item much ( can be slow )

Singly-linked lists A singly-linked list (SLL) consists of a sequence of nodes, connected by links in one direction only. Each SLL node contains a single element, plus a link to the node’s successor (or a null link if the node has no successor). An SLL header contains a link to the SLL’s first node (or a null link if the SLL is empty). 6.2 Linked List page 234

Linked List A linked list consists of a sequence of nodes connected by links, plus a header. Each node (except the last) has a successor, Each node contains a single element (object or value), plus links to its successor root Heddy Bob Jenny next next next

Linked List (2) Class Link { Object data ; Link next ; … more code here you know – stuff. } root Heddy Bob Jenny next next next

Linked List (3) Drawing (iteration ) Link thisone = root ; // I am root while( thisone != null ) { draw( thisone.data ) ; thisone = thisone.next ; } Class Link { Object data ; Link next ; … more code here you know – stuff. } Does the program crash of the root is null ? Does the program Ever stop or does it gon on for ever ? What would happen if we didn’t have the thisone = thisone.next root Heddy Bob Jenny next next Next ( null)

4 shades of insert Insert at the head Insert at the tail Insert some where in the middle Insert when the list is empty

Linked List (4) Insert at head Rockwood Next ( null) Does the program crash of the root is null ? Does the program Ever stop or does it gon on for ever ? What would happen if we didn’t have the thisone = thisone.next root Heddy Bob Jenny next next Next ( null)

Linked List (4) Insert at head 1. Make the new one’s NEXT point to what ever root was pointing at. Rockwood Next (=Heddy) Does the program crash of the root is null ? Does the program Ever stop or does it gon on for ever ? What would happen if we didn’t have the thisone = thisone.next root Heddy Bob Jenny next next Next ( null)

Linked List (4) Insert at head Make the new one’s NEXT point to what ever root was pointing at. Make root point to the one one THE END! Rockwood Next ( =Heddy) (I am ) root Does the program crash of the root is null ? Does the program Ever stop or does it gon on for ever ? What would happen if we didn’t have the thisone = thisone.next Heddy Bob Jenny next next Next ( null)

Insert at tail Was that going to be fast or slow ?

Linked List (4) Insert at tail Start with cursor pointing to root Rockwood Next ( null) (I am ) root Does the program crash of the root is null ? Does the program Ever stop or does it gon on for ever ? What would happen if we didn’t have the thisone = thisone.next Heddy Bob Jenny next next Next ( null)

Linked List (4) Insert at tail Start with cursor pointing to root Use a while loop to walk down until the next points to null Rockwood Next ( null) (I am ) root Does the program crash of the root is null ? Does the program Ever stop or does it gon on for ever ? What would happen if we didn’t have the thisone = thisone.next Heddy Bob Jenny (I am ) cusor next next Next ( null)

Linked List (4) Insert at tail Start with cursor pointing to root Use a while loop to walk down until the next points to null Rockwood Next ( null) (I am ) root Does the program crash of the root is null ? Does the program Ever stop or does it gon on for ever ? What would happen if we didn’t have the thisone = thisone.next Heddy Bob Jenny next next Next ( null) (I am ) cursor

Linked List (4) Insert at tail Start with cursor pointing to root Use a while loop to walk down until the next points to null Found Make the cursor’s next point to our new item Rockwood Next ( null) (I am ) root Does the program crash of the root is null ? Does the program Ever stop or does it gon on for ever ? What would happen if we didn’t have the thisone = thisone.next Heddy Bob Jenny next next Next ( null) (I am ) cursor

Linked List (4) Insert at tail Start with cursor pointing to root Use a while loop to walk down until the next points to null Found Make the cursor’s next point to our new item Rockwood Next ( null) (I am ) root Does the program crash of the root is null ? Does the program Ever stop or does it gon on for ever ? What would happen if we didn’t have the thisone = thisone.next Heddy Bob Jenny next next Next ( null) (I am ) cursor

Linked List (4) Insert at tail Start with cursor pointing to root Use a while loop to walk down until the next points to null Found Make the cursor’s next point to our new item Your done! Rockwood Next ( null) (I am ) root Does the program crash of the root is null ? Does the program Ever stop or does it gon on for ever ? What would happen if we didn’t have the thisone = thisone.next Heddy Bob Jenny next next Next ( null) (I am ) cursor

Insert in middle

Linked List (4) Insert at tail Start with cursor pointing to root Rockwood Next ( null) (I am ) root Does the program crash of the root is null ? Does the program Ever stop or does it gon on for ever ? What would happen if we didn’t have the thisone = thisone.next Heddy Bob Jenny next next Next ( null)

Linked List (4) Insert at tail Start with cursor pointing to root Use a while loop to walk down until the next points to null Rockwood Next ( null) (I am ) root Does the program crash of the root is null ? Does the program Ever stop or does it gon on for ever ? What would happen if we didn’t have the thisone = thisone.next Heddy Bob Jenny (I am ) cusor next next Next ( null)

Linked List (4) Insert at tail Start with cursor pointing to root Use a while loop to walk down until we get some were Copy Cursor’s ( Bob’s ) next to the new one Rockwood Next ( null) (I am ) root Heddy Bob Jenny next next Next ( null) (I am ) cursor

Linked List (4) Insert at tail Start with cursor pointing to root Use a while loop to walk down until we get some were Copy Cursor’s ( Bob’s ) next to the new one Rockwood Next ( null) (I am ) root Heddy Bob Jenny next next Next ( null) (I am ) cursor

Linked List (4) Insert at tail Start with cursor pointing to root Use a while loop to walk down until we get some were Copy Cursor’s ( Bob’s ) next to the new one ( Rockwood) Copy Rockwood to Cursor’s next Rockwood Next ( null) (I am ) root Heddy Bob Jenny next next Next ( null) (I am ) cursor

Linked List (4) Insert at tail Start with cursor pointing to root Use a while loop to walk down until we get some were Copy Cursor’s ( Bob’s ) next to the new one ( Rockwood) Copy Rockwood to Cursor’s next Rockwood Next ( null) (I am ) root Heddy Bob Jenny next next Next ( null) (I am ) cursor

Linked List (4) Insert empty head If the head is null point at new item Rockwood Next ( null) (I am ) root null

Linked List (4) Insert empty head If the head is null point at new item The end. Rockwood Next ( null) (I am ) root null

5 minute tangent on algorithm speeds 5.1 Mathematical Foundation page 158

My algorithm is faster than your algorithm Two different computers are going to run two different algorithms at different speeds Machines get faster all the time ( last years fast this next years slow ) Different programming languages

Wouldn’t it be great if we could figure out which is faster with out coding the algorithm?

time int ar[]= {1,2,3,4,5,6,7,8}; starTiming(); for( int jamjar : ar ) { System.out.println(jamjar); } endTiming(); IF you time an array you discover something intreasting. The larger the loop the longer it takes. Number of iterations

time int ar[]= {1,2,3,4,5,6,7,8}; for( int jamjar : ar ) { System.out.println(jamjar); } O(n) Number of iterations

time ArrayList list = new ArrayList( 100000 ) ; for( int i=0;i<100;i++) { list.add( I ) ; startTimer(); list.size(); endtimer(); } We call get size on a list which is getting steddly bigger – nothing take the same amount of time each time. O(1) Number of iterations

if( j2 == jamjar )System.out.println(jamjar ) ; } int ar[] = { 1 ,2,3,4,5,6,4,7,8 } ; for( int jamjar : ar ) { for( int j2 : ar ) if( j2 == jamjar )System.out.println(jamjar ) ; } What If we were looking for duplicates in an array. We would have to go over an array. For 2 times you have to run the array 4 times, For 3 times 9. For a list 4 long you get 16.

O(n2) int ar[] = { 1 ,2,3,4,5,6,4,7,8 } ; for( int jamjar : ar ) { for( int j2 : ar ) if( j2 == jamjar )System.out.println(jamjar ) ; } If we were looking for duplicates in an array. We would have to go over an array. For 2 times you have to run the array 4 times, For 3 times 9. For a list 4 long you get 16. O(n2)

O( n!) NP-Complete ( give up) Other speeds are available. O(1) - FAST/Instant O(n) - Its OK O(n2) - Oh dear O( n!) NP-Complete ( give up) Other speeds are available. O(log2(n)) - Very cool. With O notation we can figure out what the RAW speed of an algorithm is.

Comparative speeds. Linked List ArrayList l.inset(3, 0 ) ; O(1) //fast O(n)// slow l.add( 0 ) ; O(1)// fast For each loop O(n)// OK Remove( x ) For more you need to look in page XXX of the text book.

Gee wouldn’t it be good if Linked list and ArrayList had the same methods then we could use them both! They can ! Both had add()/foreach etc.

LinkedList<X> List<X> ArrayList<X> Gee wouldn’t it be good if Linked list and ArrayList had some you know abstract super class or something so I didn’t have to decide to use until later (it has) List<X> LinkedList<X> ArrayList<X>

ArrayList Vs LinkedList An arraylist uses an array for internal storage. This means it's fast for random access (e.g. get me element 99), because the array index gets you right to that element. Adding and deleting at the start or middle of the arraylist would be slow, because all the later elements have to copied forward or backward. ArrayList would also give a performance issue when the internal array fills up. The arrayList has to create a new array and copy all the elements to it.

ArrayList Vs LinkedList A linkedList is made up of a chain of nodes. Linked lists are slow when it comes to random access. Accessing element 99 means you have to traverse either forward from the beginning or backward from the end (depending on whether 99 is less than or greater than half the list size), calling next or previous, until you get to that element. Linked lists are fast for inserts and deletes anywhere in the list, since all you do is update a few next and previous pointers of a node.

Our HTML keeps breaking So you get approached by these guys. They have a start up developing an App. The app has to parts a server and a android client. Both in java. When you get close to another Weeper user to updates a list of other weepers who are near you. But it’s slow.

All these matching Tags!!

In HTML Tags must match <HTML> </HTML>

Tags can be nested <HTML> <TITLE> </TITLE>

So how to write an program which checks order in HTML and tells you if your wrong? <TITLE> </TITLE> </HTML> <HTML> <TITLE> </HTML> </TITLE>

Break Questions So how to write an program which checks order in HTML and tells you if your wrong? Who invented the algorithm?

Who invented the Algorithm? محمد بن موسى الخوارزمی‎‎; c. 780 – c. 850), Muhammad ibn Musa al-Khwarizmi Latinized as Algoritmi Persian scholar in the House of Wisdom in Baghdad who produced works in mathematics, astronomy, and geography during the Abbasid Caliphate. Also responsible for the decimal point Also  linear and quadratic equations  Algebra – you know wisdom stuff.

All these matching Tags!!

The Tags checker problem String tags[] = { "<HTML>" , "<TITLE>" , "</TITLE>" , "<BODY>" , ”<HEADER>”, }; for( String jamjar : tags ) { // Do something .. But what? }

Stack it up 101 uses of an array list 5.1 Stacks page 198

Stack ADT Requirements: 1) It must be possible to make a stack empty. 2)  It must be possible to add (‘push’) an element to the top of a stack. 3)  It must be possible to remove (‘pop’) the topmost element from a stack. 4)  It must be possible to test whether a stack is empty. 5)  It should be possible to access the topmost element in a stack without removing it.

Stack ADT: contract (1) Possible contract, expressed as a Java interface*: // Make this stack empty. public void push(Object elem); public interface Stack { // Add elem as the top element of this stack. // Each Stack object is a stack whose elements are objects. public boolean empty(); // Return true if and only if this stack is empty. public Object pop(); // Remove and return the element at the top of this stack. public Object peek(); // Return the element at the top of this stack. } public void clear ();

The Tags checker solutution import java.util.*; String tags[] = { "HTML" , "TITLE" , "TITLE" , "BODY" , "H1" , "H1" , "BODY" ,"HTML" }; Stack<String> myStack=new Stack<String>() ; for( String jamjar : tags ) { if( jamjar.equals( myStack.peek()) {myStack.pop(); } else { myStack.push( jamjar ) ; } } if( ! myStack.empty()) { println("ERROR AT TAG "}+ myStack.pop(); }

Lists and Stacks

Maze solutions -

Maze solutions -

Maze solutions - I’m stuck ( no where to go) So I pop back to some where I had a choice.

Maze solutions - I’m stuck ( no where to go) So I pop back to some where I had a choice.

Maze solutions - I’m stuck ( no where to go) So I pop back to some where I had a choice.

Maze solutions - I’m stuck ( no where to go) So I pop back to some where I had a choice.

Maze solutions - I’m stuck ( no where to go) So I pop back to some where I had a choice.

Maze solutions - I’m stuck ( no where to go) So I pop back to some where I had a choice.

Maze solutions - I’m stuck ( no where to go) So I pop back to some where I had a choice.

Lists and Stacks what could we use make a Stack ? It needs push() ( say something.add() at end ) It needs a peek() ( say something.get() ) It needs pop() ( say something.remove() ) It needs isEmpty() ( say something.empty() )

Queues – could there be anything more English? 5.2 Queues page 214

Queues First in first out – They are so English and Fun. I’m sure we can do something with them?

Queueing traffic No to boring – let’s ask the start up guy….

We have ticket only events We have ticket only events. Members should come first but the order should be kept. So you get approached by these guys. They have a start up developing an App. The app has to parts a server and a android client. Both in java. When you get close to another Weeper user to updates a list of other weepers who are near you. But it’s slow.

BEFORE AFTER 1 a 2 b 3 4 5 6 c d 7 e a b c d e 1 2 3 4 5 6 7 members only Non Members

Bad idea: Good idea: use a sorting algorithm. Time complexity is O(n log n) at best. Good idea: use a demerging algorithm. Time complexity is O(n). Subliminal message ( Trust me on this )

Input 1 a 2 b 3 4 5 6 c d 7 e queN queM members only Non Members

Input a 2 b 3 4 5 6 c d 7 e queN queM 1 members only Non Members

Input 2 b 3 4 5 6 c d 7 e queN a queM 1 members only Non Members

Input b 3 4 5 6 c d 7 e queN a queM 1 2 members only Non Members

Input 3 4 5 6 c d 7 e queN a b queM 1 2 members only Non Members

Input 4 5 6 c d 7 e queN a b queM 1 2 3 members only Non Members

Input 6 c d 7 e queN a b queM 1 2 3 4 5 members only Non Members

Input 6 c d 7 e queN a b queM 1 2 3 4 5 members only Non Members

Finish with queN a b c d e queM 1 2 3 4 5 6 7 members only Non Members

Finish with queN a b c d e queM 1 2 3 4 5 6 7 members only Non Members

Finish with a b c d e 1 2 3 4 5 6 7 members only Non Members

Queue ADT: requirements It must be possible to make a queue empty. It must be possible to test whether a queue is empty. It must be possible to obtain the length of a queue. It must be possible to add an element at the rear of a queue. It must be possible to remove the front element from a queue. It must be possible to access the front element in a queue without removing it.

Queue ADT: ( possible ) contract public interface Queue { public boolean isEmpty (); // Return true if and only if this queue is empty. public int size (); // Return this queue’s length. public Object getFirst (); // Return the element at the front of this queue. public void clear (); // Make this queue empty. public void addLast (Object elem); // Add elem as the rear element of this queue. public Object removeFirst (); // Remove and return the front element of this queue. }

Queue ADT: ( possible ) contract public interface Queue<E> extends Collection<E> { E element(); boolean offer(E o); E peek(); E poll(); E remove(); }

Queue ADT: ( possible ) contract Each Queue method exists in two forms: one throws an exception if the operation fails the other returns a special value (either null or false, depending on the operation). Throws exception Returns special value Insert add(e) offer(e) Remove remove() poll() Examine element() peek() Why would an add fail ?

The java.util.LinkedList class provides all the Queue operations, for example import java.util.LinkedList; LinkedList<String> queue = new LinkedList<String>(); queue.addLast("Homer"); queue.addLast("Marge"); queue.addLast("Bart"); queue.addLast("Lisa"); queue.addLast("Maggie"); System.out.println(queue.removeFirst());

What have we covered? LinkedList List Stacks Queues O-notation If you can’t decided between array list and linked List. Stacks Useful if you want to… ? Queues Useful if you want to … O-notation Useful to compare different algorthiums

On the paper you have, to write two things What are the two key things you have learned during this lecture? For real I’m interested in the first two things youremember. Do you have any questions about what you have learned so far?