430 likes | 685 Views
Queues. The Queue ADT stores arbitrary objects Insertions and deletions follow the first-in first-out scheme Insertions are at the rear of the queue and removals are at the front of the queue Main queue operations: enqueue (object): inserts an element at the end of the queue
E N D
Queues Queues
The Queue ADT stores arbitrary objects Insertions and deletions follow the first-in first-out scheme Insertions are at the rear of the queue and removals are at the front of the queue Main queue operations: enqueue(object): inserts an element at the end of the queue object dequeue(): removes and returns the element at the front of the queue Auxiliary queue operations: object front(): returns the element at the front without removing it integer size(): returns the number of elements stored boolean isEmpty(): indicates whether no elements are stored Exceptions Attempting the execution of dequeue or front on an empty queue throws an EmptyQueueException The Queue ADT (§4.3) Queues
Queue Example Operation Output Q enqueue(5) – (5) enqueue(3) – (5, 3) dequeue() 5 (3) enqueue(7) – (3, 7) dequeue() 3 (7) front() 7 (7) dequeue() 7 () dequeue() “error” () isEmpty() true () enqueue(9) – (9) enqueue(7) – (9, 7) size() 2 (9, 7) enqueue(3) – (9, 7, 3) enqueue(5) – (9, 7, 3, 5) dequeue() 9 (7, 3, 5) Queues
Applications of Queues • Direct applications • Waiting lists, bureaucracy • Access to shared resources (e.g., printer) • Multiprogramming • Indirect applications • Auxiliary data structure for algorithms • Component of other data structures Queues
Queue ADT • Operations • Enqueue, Dequeue, Peek, isEmpty • Implementation: • Circular Array (Weiss), • Linked List, • Circular Linked List (text) • Application: • Level-Order Tree Traversal
Implementing a Queue • Using Vector /Array • requires estimate of maximum queue length • may grow dynamically • Ø = empty slots • Can contain varied data/objects (not necessarily homogeneous) 212 rules! Ø Ø Ø 28-17 Golf #1 front rear
Implementing a Queue • Using Linked List • flexible, adjusts to problem size • implementing a linked list • nodes and references/links/pointers front Ø 212 rules! 28-17 Golf #1 rear
Implementing a Queue 0 1 2 3 4 5 6 7 8 2 -1 7 -1 1 4 3 6 0 Ø • Using Linked List • implementing a linked list • cursor implementation Golf #1 Ø Ø front = 5 212 rules! rear = 1 28-17 freelist = 8 Ø Ø Ø
Use an array of size N in a circular fashion Two variables keep track of the front and rear f index of the front element r index immediately past the rear element Array location r is kept empty Q 0 1 2 f r Q 0 1 2 r f Array-based Queue normal configuration wrapped-around configuration Queues
Q 0 1 2 f r Q 0 1 2 r f Queue Operations • We use the modulo operator (remainder of division) Algorithmsize() return(N-f +r) mod N AlgorithmisEmpty() return(f=r) Queues
Q 0 1 2 f r Q 0 1 2 r f Queue Operations (cont.) • Operation enqueue throws an exception if the array is full • This exception is implementation-dependent Algorithmenqueue(o) ifsize()=N 1then throw FullQueueException else Q[r] o r(r + 1) mod N Queues
Q 0 1 2 f r Q 0 1 2 r f Queue Operations (cont.) • Operation dequeue throws an exception if the queue is empty • This exception is specified in the queue ADT Algorithmdequeue() ifisEmpty()then throw EmptyQueueException else oQ[f] f(f + 1) mod N returno Queues
Queue Interface in Java • Java interface corresponding to our Queue ADT • Requires the definition of class EmptyQueueException • No corresponding built-in Java class public interfaceQueue{ public int size(); public boolean isEmpty(); public Object front()throwsEmptyQueueException; public voidenqueue(Object o); public Object dequeue()throwsEmptyQueueException;} Queues
Antrian Mobil Class Mobil{ ….} Class AntrianMobil implements Queue{ Mobil []data; int N,r,f; public AntrianMobil(int n){ N = n; data = new Mobil[N]; r = 0; f = 0; } public int size(){} public boolean isEmpty(){} public Object front()throwsEmptyQueueException{} public voidenqueue(Object o){} public Object dequeue()throwsEmptyQueueException{} } Queues
The Queue 2 . Service the 3 . Enqueue the 1 . Deque the next element serviced element next element Shared Service Application: Round Robin Schedulers • We can implement a round robin scheduler using a queue, Q, by repeatedly performing the following steps: • e = Q.dequeue() • Service element e • Q.enqueue(e) Queues
Implementasi RR Class proses { int id, timeX; proses(int id, int time){ithis.id = id; timeX = time;} } //inisi Input N - banyaknyaproses Input t - time slice BuatAntrian Q For I <- 0 to N do input proseske-I enQ(proses_i) end for // RR While (! Q.isEmpty()){ proses p = deQ(); p.timeX = p.timeX – t if (p.TimeX > 0) enQ(p) } Queues
Queue Abstract Data Type • A queue is a linear collection where the elements are added to one end and removed from the other end • The processing is first in, first out (FIFO) • The first element put on the queue is the first element removed from the queue • Think of a line of people waiting for a bus (The British call that “queuing up”)
A Conceptual View of a Queue Rear of Queue (or Tail) Front of Queue (or Head) Removing an Element Adding an Element
Queue Terminology • We enqueue an element on a queue to add one • We dequeue an element off a queue to remove one • We can also examine the first element without removing it • We can determine if a queue is empty or not and how many elements it contains (its size) • The L&C QueueADT interface supports the above operations and some typical class operations such as toString()
Queue ADT Interface <<interface>> QueueADT<T> + enqueue(element : T) : void + dequeue () : T + first() : T + isEmpty () : bool + size() : int + toString() : String
Queue Design Considerations • Although a queue can be empty, there is no concept for it being full. An implementation must be designed to manage storage space • For first and dequeue operation on an empty queue, this implementation will throw an exception • Other implementations could return a value null that is equivalent to “nothing to return”
Queue Design Considerations • No iterator method is provided • That would be inconsistent with restricting access to the first element of the queue • If we need an iterator or other mechanism to access the elements in the middle or at the end of the collection, then a queue is not the appropriate data structure to use
The java.util.Queue Interface • The java.util.Queue interface is in the Java Collections API (extends Collection) • However, it is only an interface and you must use an implementing class • LinkedList is the most commonly used implementing class • For a queue of type objects: Queue<type> myQueue = new LinkedList<type>();
The java.util.Queue Interface • The names of the methods are different • Enqueue is done using: boolean offer(T element) // returns false if full • Dequeue is done using either: T poll() // returns null value if empty T remove() // throws an exception if empty • Peek is done using either: T peek() // returns null value if empty T element() // throws an exception if empty
Using Vectors • You could implement a deque with java.util.Vector: • addAtFront(Object) insertElementAt(Object, 0) • addAtRear(Object item) add(Object) • getFromFront() remove(0) • getFromRear() remove(size() – 1) • Would this be a good implementation? • Why or why not?
We can treat the array holding the queue elements as circular (joined at the ends) Elements were added to this queue in the order 11, 22, 33, 44, 55, and will be removed in the same order Use: front = (front + 1) % myQueue.length;and: rear = (rear + 1) % myQueue.length; 0 1 2 3 4 5 6 7 myQueue: 44 55 11 22 33 front = 5 rear = 1 Circular arrays
If the queue were to become completely full, it would look like this: If we were then to remove all eight elements, making the queue completely empty, it would look like this: 0 1 2 3 4 5 6 7 myQueue: 44 55 66 77 88 11 22 33 front = 5 rear = 4 rear = 4 0 1 2 3 4 5 6 7 myQueue: front = 5 Full and empty queues This is a problem!
Solution #1: Keep an additional variable Solution #2: (Slightly more efficient) Keep a gap between elements: consider the queue full when it has n-1 elements 0 1 2 3 4 5 6 7 myQueue: 44 55 66 77 88 11 22 33 count = 8 front = 5 rear = 4 rear = 3 0 1 2 3 4 5 6 7 myQueue: 44 55 66 77 11 22 33 front = 5 Full and empty queues: solutions
Linked-list implementation of queues • In a queue, insertions occur at one end, deletions at the other end • Operations at the front of a singly-linked list (SLL) are O(1), but at the other end they are O(n) • Because you have to find the last element each time • BUT: there is a simple way to use a singly-linked list to implement both insertions and deletions in O(1) time • You always need a pointer to the first thing in the list • You can keep an additional pointer to the last thing in the list
SLL implementation of queues • In an SLL you can easily find the successor of a node, but not its predecessor • Remember, pointers (references) are one-way • If you know where the last node in a list is, it’s hard to remove that node, but it’s easy to add a node after it • Hence, • Use the first element in an SLL as the front of the queue • Use the last element in an SLL as the rear of the queue • Keep pointers to both the front and the rear of the SLL
Node to be enqueued 17 lastfirst 44 23 97 Enqueueing a node To enqueue (add) a node: Find the current last node Change it to point to the new last node Change the last pointer in the list header
lastfirst 44 97 23 17 Dequeueing a node • To dequeue (remove) a node: • Copy the pointer from the first node into the header
Queue implementation details • With an array implementation: • you can have both overflow and underflow • you should set deleted elements to null • With a linked-list implementation: • you can have underflow • overflow is a global out-of-memory condition • there is no reason to set deleted elements to null
Deques • A deque is a double-ended queue • Insertions and deletions can occur at either end • Implementation is similar to that for queues • Deques are not heavily used • You should know what a deque is, but we won’t explore them much further
A queue ADT • Java does not provide a queue class • Here is a possible queue ADT: • Queue(): the constructor • boolean empty() • Object enqueue(Object item): add at element at the rear • Object dequeue(): remove an element from the front • Object peek(): look at the front element • int search(Object o): Returns the 1-based position from the front of the queue
A deque ADT • Java does not provide a deque class • Here is a possible deque ADT: • Deque(): the constructor • boolean empty() • Object addAtFront(Object item) • Object addAtRear(Object item) • Object getFromFront() • Object getFromRear() • Object peekAtFront() • Object peekAtRear() • int search(Object o): Returns the 1-based position from the front of the deque
Using Vectors • You could implement a deque with java.util.Vector: • addAtFront(Object) insertElementAt(Object, 0) • addAtRear(Object item) add(Object) • getFromFront() remove(0) • getFromRear() remove(size() – 1) • Would this be a good implementation? • Why or why not?
11. (wajib) Misalkanandamendapatkankesempatanuntukmembuatsistempelayananpelangganpadasuaturestoran. Restoraninimempunyai N buahmeja yang dikelilingi 4 buahkursi. Karenaterkenalfavoritmakarestoraniniselaludipadatiolehpelangganpada jam kerjanya. Bukasetiapharimulai jam 08 pagisampai jam 8 sore. Setiappelanggaharuspesantempatterlebihdahulu minimal 2 jam sebelumdiamasuk. Adatigapilihanpemesanan : VIP, EXPRESS, BIASA. Jatahmasing-masingkelas 1/3 daritempat yang disediakan. Masing-masingpelanggandapatmemesan 0 sampai M menu yang disediakan. Prosespelayananakandikerjakanberdasarkanantrian per kelas. Kelas VIP, EXPRESS kemudian BIASA. Kelas VIP dilayaniterlebihdahulu, kemudian Express danterakhirkelas BIASA. Biayaakandihitungberdasarkan item yang dipesanditambahbiayakelasmasing-masing 0.2%, 0,1 % dan 0% untuk VIP, EXPRESS dan BIASA daribiayapelayanan. Besarnyabiayapelayanansebesar Rp.20.000 per meja,-. Jumlahbiaya yang harusdibayarmasing-masingpelangganmeliputi : biayapelayanan + biayakelas + Akumulasibiaya item + pajak (10 % darinettoAkumulasi item). Seorangpelanggandapatmemesanlebihdariduamejadengansyaratjikamejapadakelas VIP penuhbolehmanambahmejadarikelasBiasamaksimalkuota (5% darijatahmejakelas BIASA). Jikakelasmejakelas EXPRESS dan BIASA penuhtidakbolehnambahmejadarikelas lain. Queues
2 (pilihan) • Misalkanandadisuruhmembuat program untukmenatapenempatanbarangpadasuaturakdenganketentuansebagaiberikut : • Setiapbarangmempunyaiattribut : • Id, merk, jenis, harga • Rakterbagidalamdua slot (slot1 dan slot2) • Slot 1 akanditempatibarangdengantipejenis 1 denganharga > X. Selainituditempatkandi slot 2. • Pengeluaranbarangselaludimulaidaribarang yang mempunyaijenis 1 denganharga > X. Setelahbarangdengankriteriainihabisbarulahbarang yang lainnya.
3. pilihan • Suatupabrikmemproduksisuatujenisbarangdengankualitas A, kualitas B dan C. Pembuatanbarangditentukanberdasarkanketersediaanbahanbakukualitas 1, 2 dan 3. Jikatersediabahanbakukualitas 1 makadiproduksilahbarangkualitas A demikianseterusnya. Setiapproduksimelibatkanduabuahmesin M1 dan M2. Untuktetapmenjagakualitaspembuatankulitasbarang A harusdikerjakanterlebihdahulubarukualitas B dan C. • Susunlah program untukmensimulasimasalahini.
Struktur Tugas • Halamanjudul + KodeTugas (K[01]_[C]_T[03]) (5%) • Deskripsimasalah (5 %) • Rancangansolusi (20 %) • Rancanganstruktur data umum (10 %) • Rancanganclass (10 %) • Coding + komentar (40 %) • Ujicoba(10 %) • Spek 1 • Spek 2 • Spek 3 • … • Format A4 , 1 spasi, khususuntuk coding (courier new 9, bold) Queues