Presentation is loading. Please wait.

Presentation is loading. Please wait.

Priority Queue Erick, Eka, Reddy © Sekolah Tinggi Teknik Surabaya 1.

Similar presentations


Presentation on theme: "Priority Queue Erick, Eka, Reddy © Sekolah Tinggi Teknik Surabaya 1."— Presentation transcript:

1 Priority Queue Erick, Eka, Reddy © Sekolah Tinggi Teknik Surabaya 1

2 » Priority Queue ADT +Keys, Priorities, and Total order Relations +Sorting with a Priority Queue » Priority Queue implementation +Implementation with an unsorted sequence +Implementation with a sorted sequence 2 © Sekolah Tinggi Teknik Surabaya

3 3 » A priority queue stores a collection of entries / node » Each node is a pair (key, value) » Main methods of the Priority Queue ADT ˃insert(k, x) inserts an node with key k and value x ˃removeMin() removes and returns the node with smallest key » Additional methods ˃min() returns, but does not remove, an node with smallest key ˃size(), isEmpty() » Applications: ˃Standby flyers ˃Auctions ˃Stock market

4 » Suppose that you have a few assignments from different courses. Which assignment will you want to work on first? » You set your priority based on due days. Due days are called keys. 4 © Sekolah Tinggi Teknik Surabaya CoursePriorityDue day Database Systems2October 3 Introduction to C++4October 10 Data Structure & Algorithm1September 29 Structured Systems Analysis 3October 7

5 » Any of the attributes, Student Name, Student Number, or Final Score can be used as keys. » Note: Keys may not be unique (Final Score). 5 © Sekolah Tinggi Teknik Surabaya Student NameStudent NumberFinal Score Bill Scott11010265 Bob Jones11014076 Alan Smith11024386 Susan Kane11017680

6 » Suppose we are looking for tires for a passenger car. How can we weight the tires so we can select the tires? » The key may consist of not only one attribute such as price. In fact, we want to consider factors such as brands and warranty as well. » So the key may be more complex than just one value. 6 © Sekolah Tinggi Teknik Surabaya BrandPriceWarranty (km) Motormaster$61.49110,000 Goodyear$98.99220,000 Michelin$101.99150,000

7 7 © Sekolah Tinggi Teknik Surabaya » Keys in a priority queue can be arbitrary objects on which an order is defined » Two distinct entries in a priority queue can have the same key » Mathematical concept of total order relation  ˃ Reflexive property: x  x ˃ Antisymmetric property: x  y  y  x  x = y ˃ Transitive property: x  y  y  z  x  z

8 » Not everything can have a total order relation. » Non-example: » For 2-D vectors v1 = (x1, x2) and v2 = (x3, x4), define the following ordering rule: » v1  v2 if x2 - x1 == x4 - x3 » Then we have » 4 - 1 = 7 - 4 » Therefore, (1, 4)  (4, 7) and (4, 7)  (1, 4). » But (1,4)  (7, 4), namely, the relation does not satisfy the » antisymmetric property. 8 © Sekolah Tinggi Teknik Surabaya

9 » If a comparison rule defines a total order relation, it will never lead to a comparison contradiction. » the smallest key: If we have a finite number of elements with a total order relation, then the smallest key, denoted by k min, is well-defined: k min is the key that satisfies k min  k for any other key k. » Being able to find the smallest key is very important because in many cases, we want to have the element with the smallest key. 9 © Sekolah Tinggi Teknik Surabaya

10 » priority queue: A container of elements, each having an associated key that is provided at the time the element is inserted. » The two fundamental methods of a priority queue P: 10 © Sekolah Tinggi Teknik Surabaya insertItem(k,e):Insert an element e with key k into P. removeMin():Return and remove from P an element with the smallest key.

11 11 © Sekolah Tinggi Teknik Surabaya » We can use a priority queue to sort a set of comparable elements 1.Insert the elements one by one with a series of insert operations 2.Remove the elements in sorted order with a series of removeMin operations » The running time of this sorting method depends on the priority queue implementation Algorithm PQ-Sort(S, C) Input sequence S, comparator C for the elements of S Output sequence S sorted in increasing order according to C P  priority queue with comparator C while not S.isEmpty () e  S.removeFirst () P.insert (e, 0) while not P.isEmpty() e  P.removeMin().key() S.insertLast(e)

12 » We have a sequence S with 6 integers (elements). Also we have an empty priority queue P. » While S is not empty insert to P 12 © Sekolah Tinggi Teknik Surabaya

13 » After the first step, all the elements are now in the priority queue, with themselves as keys. 13 © Sekolah Tinggi Teknik Surabaya

14 » The first three elements have been extracted from P and inserted into S in order. The element with the smallest key in P now is 4,4, which will be extracted next time. 14 © Sekolah Tinggi Teknik Surabaya

15 » After the second step: Now the elements are sorted in S. 15 © Sekolah Tinggi Teknik Surabaya

16 » The priority queue abstract data type supports the following methods: 16 © Sekolah Tinggi Teknik Surabaya size():Return the number of elements in P. Input: None; Output: Integer isEmpty():Test whether P is empty. Input: None; Output: Boolean inserItem(k,e):Insert a new element e with key k into P. Input: Objects k (key) and e (element); Output: None minElement():Return (but do not remove) an element of P with the smallest key; an error condition occurs if the priority queue is empty. Input: None; Output: Object (element) minKey():Return a smallest key in P; an error condition occurs if the priority queue is empty. Input: None; Output: Object (key) removeMin():Remove from P and return an element with the smallest key; an error condition occurs if the priority queue is empty. Input: None; Output: Object (element)

17 » The following table shows a series of operations and their effects on an initially empty priority queue P. 17 © Sekolah Tinggi Teknik Surabaya Operation OutputPriority Queue insertItem(5,A)-{(5,A)} insertItem(9,C)-{(5,A),(9,C)} insertItem(3,B)-{(3,B),(5,A),(9,C)} insertItem(7,D)-{(3,B),(5,A),(7,D),(9,C)} minElement()B{(3,B),(5,A),(7,D),(9,C)} minKey()3{(3,B),(5,A),(7,D),(9,C)} removeMin()B{(5,A),(7,D),(9,C)} size()3{(5,A),(7,D),(9,C)} removeMin()A{(7,D),(9,C)} removeMin()D{(9,C)} removeMin()C{} removeMin()“error”{} isEmpty()true{}

18 » Node Class » Icomparable ADT 18 © Sekolah Tinggi Teknik Surabaya

19 19 © Sekolah Tinggi Teknik Surabaya » A node in a priority queue is simply a key- value pair » Priority queues store nodes to allow for efficient insertion and removal based on keys » Methods: ˃key(): returns the key for this node ˃value(): returns the value associated with this node » As C# class: public class Node { public int key; public T value; }

20 20 © Sekolah Tinggi Teknik Surabaya » A comparator encapsulates the action of comparing two objects according to a given total order relation » A generic priority queue uses an auxiliary comparator » The comparator is external to the keys being compared » When the priority queue needs to compare two keys, it uses its comparator » The primary method of the Comparator ADT: ˃compare(x, y): Returns an integer i such that i 0 if a > b; an error occurs if a and b cannot be compared.

21 » Let S be a sequence. A pair of key and element is denoted as p=(k,e). With an unsorted sequence, we use the method insertLast(p) of S to implement insertItem(k,e) of the priority queue P. » To perform operations including minElement, minKey, and removeMin, we have to inspect all the elements of the sequence S to find the element with the smallest key. 21 © Sekolah Tinggi Teknik Surabaya

22 » Assume we have the elements stored in an unsorted sequence show here. » To perform the removeMin() operation, we have to inspect all elements to find the element (0,0) that has the smallest key. 22 © Sekolah Tinggi Teknik Surabaya

23 » Let S be a sequence. A pair of key and element is denoted as p=(k,e). With an sorted sequence, we can easily extract the element with the smallest key with the combination of methods remove() and first() of S. » However, to perform operation insertItem, we need to scan through the sequence S to find the apropriate position to insert the new element and key. 23 © Sekolah Tinggi Teknik Surabaya

24 » To insert the pair (6,6), we have to scan through the sequence until we find the right place (between (4,4) and (7,7)). 24 © Sekolah Tinggi Teknik Surabaya

25 MethodUnsorted SSorted S size, isEmptyfast insertItemfast O(n) minElement, minKey, removeMin O(n) fast 25 © Sekolah Tinggi Teknik Surabaya » Assume that the size of the sequence is n.

26 26 Microsoft Inheritance Use in the small, when a derived class "is-a" base class –enables code reuse –enables design reuse & polymorphic programming Example: –a Student is-a Person Undergraduate Person StudentEmployee GraduateStaffFaculty

27 27 Microsoft Implementation C# supports single inheritance –public inheritance only (C++ parlance) – base keyword gives you access to base class's members public class Student : Person { private int m_ID; public Student(string name, int age, int id) // constructor :base(name, age) { this.m_ID = id; } Student Person

28 28 Microsoft Binding C# supports both static and dynamic binding –determined by absence or presence of virtual keyword –derived class must acknowledge with new or override public class Person {. // statically-bound public string HomeAddress() { … } // dynamically-bound public virtual decimal Salary() { … } } public class Student : Person {. public new string HomeAddress() { … } public override decimal Salary() { … } }

29 29 Microsoft All classes inherit from System.Object

30 30 Microsoft Part 4 Interfaces…

31 31 Microsoft Interfaces An interface represents a design Example: –the design of an object for iterating across a data structure –interface = method signatures only, no implementation details! –this is how foreach loop works… public interface IEnumerator { void Reset(); // reset iterator to beginning bool MoveNext(); // advance to next element object Current { get; } // retrieve current element }

32 32 Microsoft Why use interfaces? Formalize system design before implementation –especially helpful for PITL (programming in the large) Design by contract –interface represents contract between client and object Decoupling –interface specifies interaction between class A and B –by decoupling A from B, A can easily interact with C, D, …

33 33 Microsoft.NET is heavily influenced by interfaces IComparable ICloneable IDisposable IEnumerable & IEnumerator IList ISerializable IDBConnection, IDBCommand, IDataReader etc.

34 34 Microsoft Example Sorting –FCL contains methods that sort for you –sort any kind of object –object must implement IComparable object[] students; students = new object[n]; students[0] = new Student(…); students[1] = new Student(…);. Array.Sort(students); public interface IComparable { int CompareTo(object obj); }

35 35 Microsoft To be a sortable object… Sortable objects must implement IComparable Example: –Student objects sort by id public class Student : Person, IComparable { private int m_ID;. int IComparable.CompareTo(Object obj) { Student other; other = (Student) obj; return this.m_ID – other.m_ID; } base classinterface Student Person

36 36 Microsoft Summary Object-oriented programming is *the* paradigm of.NET C# is a fully object-oriented programming language –fields, properties, indexers, methods, constructors –garbage collection –single inheritance –interfaces Inheritance? –consider when class A "is-a" class B –but you only get single-inheritance, so make it count Interfaces? –consider when class C interacts with classes D, E, F, … –a class can implement any number of interfaces


Download ppt "Priority Queue Erick, Eka, Reddy © Sekolah Tinggi Teknik Surabaya 1."

Similar presentations


Ads by Google