Download presentation
Presentation is loading. Please wait.
1
KF5008 Collections(2) Dr Nick Dalton
2
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.
3
Last weeks break question
Who invented the communication technology behind the modern mobile phone? Last weeks break question
4
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.
5
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.
7
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?
8
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.
9
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 )
10
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
11
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
12
Linked List (2) Class Link { Object data ; Link next ;
… more code here you know – stuff. } root Heddy Bob Jenny next next next
13
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)
14
4 shades of insert Insert at the head Insert at the tail
Insert some where in the middle Insert when the list is empty
15
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)
16
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)
17
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)
18
Insert at tail Was that going to be fast or slow ?
19
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)
20
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)
21
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
22
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
23
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
24
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
25
Insert in middle
26
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)
27
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)
28
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
29
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
30
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
31
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
32
Linked List (4) Insert empty head
If the head is null point at new item Rockwood Next ( null) (I am ) root null
33
Linked List (4) Insert empty head
If the head is null point at new item The end. Rockwood Next ( null) (I am ) root null
34
5 minute tangent on algorithm speeds
5.1 Mathematical Foundation page 158
35
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
36
Wouldn’t it be great if we could figure out which is faster with out coding the algorithm?
37
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
38
time int ar[]= {1,2,3,4,5,6,7,8}; for( int jamjar : ar ) { System.out.println(jamjar); } O(n) Number of iterations
39
time ArrayList list = new ArrayList( ) ; 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
40
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.
41
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)
42
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.
43
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.
44
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.
45
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>
46
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.
47
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.
48
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.
49
All these matching Tags!!
50
In HTML Tags must match <HTML> </HTML>
51
Tags can be nested <HTML> <TITLE> </TITLE>
52
So how to write an program which checks order in HTML and tells you if your wrong?
<TITLE> </TITLE> </HTML> <HTML> <TITLE> </HTML> </TITLE>
53
Break Questions So how to write an program which checks order in HTML and tells you if your wrong? Who invented the algorithm?
54
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.
55
All these matching Tags!!
56
The Tags checker problem
String tags[] = { "<HTML>" , "<TITLE>" , "</TITLE>" , "<BODY>" , ”<HEADER>”, }; for( String jamjar : tags ) { // Do something .. But what? }
57
Stack it up 101 uses of an array list 5.1 Stacks page 198
58
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.
59
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 ();
60
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(); }
61
Lists and Stacks
62
Maze solutions -
63
Maze solutions -
64
Maze solutions - I’m stuck ( no where to go)
So I pop back to some where I had a choice.
65
Maze solutions - I’m stuck ( no where to go)
So I pop back to some where I had a choice.
66
Maze solutions - I’m stuck ( no where to go)
So I pop back to some where I had a choice.
67
Maze solutions - I’m stuck ( no where to go)
So I pop back to some where I had a choice.
68
Maze solutions - I’m stuck ( no where to go)
So I pop back to some where I had a choice.
69
Maze solutions - I’m stuck ( no where to go)
So I pop back to some where I had a choice.
70
Maze solutions - I’m stuck ( no where to go)
So I pop back to some where I had a choice.
71
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() )
72
Queues – could there be anything more English?
5.2 Queues page 214
73
Queues First in first out – They are so English and Fun.
I’m sure we can do something with them?
74
Queueing traffic No to boring – let’s ask the start up guy….
75
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.
76
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
77
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 )
78
Input 1 a 2 b 3 4 5 6 c d 7 e queN queM members only Non Members
79
Input a 2 b 3 4 5 6 c d 7 e queN queM 1 members only Non Members
80
Input 2 b 3 4 5 6 c d 7 e queN a queM 1 members only Non Members
81
Input b 3 4 5 6 c d 7 e queN a queM 1 2 members only Non Members
82
Input 3 4 5 6 c d 7 e queN a b queM 1 2 members only Non Members
83
Input 4 5 6 c d 7 e queN a b queM 1 2 3 members only Non Members
84
Input 6 c d 7 e queN a b queM 1 2 3 4 5 members only Non Members
85
Input 6 c d 7 e queN a b queM 1 2 3 4 5 members only Non Members
86
Finish with queN a b c d e queM 1 2 3 4 5 6 7 members only Non Members
87
Finish with queN a b c d e queM 1 2 3 4 5 6 7 members only Non Members
88
Finish with a b c d e 1 2 3 4 5 6 7 members only Non Members
89
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.
90
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. }
91
Queue ADT: ( possible ) contract
public interface Queue<E> extends Collection<E> { E element(); boolean offer(E o); E peek(); E poll(); E remove(); }
92
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 ?
93
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());
94
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
96
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?
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.