Queues, Vectors

Download Report

Transcript Queues, Vectors

Foundations of Software Design
Fall 2002
Marti Hearst
Lecture 13: Queues and Vectors
1
Queues
http://www.lib.uconn.edu/DoddCenter/ASC/Wilcox/Students.htm
2
Queue
• Container of objects that are inserted and
removed according to the principle of
– First-in-first-out
– FIFO
• Objects can be inserted at any time, but only
the least recently inserted can be removed at
any time.
• Operations:
– Enqueue: put item onto queue
– Dequeue: remove item from queue
3
A Comparison
• How are queues similar to / different from
stacks?
4
Queue Running Times
• What is the running time of each operation?
• Enqueue
O(1)
• Dequeue
O(1)
• isEmpty()
O(1)
5
6
How are Queues Used?
• Queues are used extensively in
– The OS
• For scheduling processes to receive resources
– Computer networking
• For keeping storing and sending network packets
7
Use of Queues in the OS
Processes waiting
in a queue
http://courses.cs.vt.edu/~csonline/OS/Lessons/Processes/index.html
8
Use of Queues
in Distributed
Systems
Animation by
Remzi Arpaci-Dusseau
9
Sequences, Lists, & Vectors
• There are many ways to implement sequences
of items
• In order of abstractness:
– Sequence > List > Vector
• Know about Vectors in Java
– Can be more intuitive to program with
– But can be less efficient
– Implements the Enumeration interface
10
Java
Vector
API
11
Java
Vector
API
12
Java Vectors
• When you insert an element into a Java
Vector, it moves all the elements behind the
new one back one position
– insertElementAt
• When you delete an element, is moves all the
elements behind that one up one position
– removeElementAt
– removeElement
13
Vectors in Java
• How do they differ from arrays?
– Can grow the length dynamically
– Can insert items into any position
– Have a different API (set of method calls)
• What are the running times of the operations?
– boolean isEmpty()
• O(1)
– Object firstElement()
• O(1)
– boolean contains(Object elem)
• O(n)
– Object elementAt(int index)
• O(1)
14
A Comparison
• How are queues similar to / different from
vectors?
15
Let’s Write Code!
• Implement a Queue using Vectors
• What is the API?
–
–
–
–
–
void enQueue(Object o)
Object deQueue()
int size ()
boolean isEmpty ()
Object front ()
16
17
18