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

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

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

Data Structure

Priority QueueErick, Eka, Reddy

© Sekolah Tinggi Teknik Surabaya

1

Outlines» 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

Priority Queue Concept

3

© Sekolah Tinggi Teknik Surabaya

» 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

Keys (1)» 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

Course Priority Due dayDatabase Systems 2 October 3Introduction to C++ 4 October 10Data Structure & Algorithm 1 September 29Structured Systems Analysis

3 October 7

Example: Student records

» 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 Name Student Number Final ScoreBill Scott 110102 65Bob Jones 110140 76Alan Smith 110243 86Susan Kane 110176 80

Example (2)

» 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

Brand Price Warranty (km)Motormaster $61.49 110,000Goodyear $98.99 220,000Michelin $101.99 150,000

Total Order Relations

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

Total Order Relations (2)» 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

Comparison» 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 kmin, is well-defined: kmin is the key that satisfies kmin 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

PQ Summary» 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.

Priority Queue Sorting

11

© Sekolah Tinggi Teknik Surabaya

» We can use a priority queue to sort a set of comparable elements1. 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 SOutput sequence S sorted in increasing order according to CP priority queue with comparator Cwhile not S.isEmpty ()

e S.removeFirst ()P.insert (e, 0)

while not P.isEmpty()e P.removeMin().key()

S.insertLast(e)

Sorting Example (1)» 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

4 0 7 8 2 1

S

P

Sorting Example : Step 1» After the first step, all the elements are

now in the priority queue, with themselves as keys.

13

© Sekolah Tinggi Teknik Surabaya

S

4,40,0 7,7 8,82,21,1

P

Sorting Example : Step 2» 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

0 21

S

4,4 7,7 8,8

P

Sorting Example : Final» After the second step: Now the

elements are sorted in S.

15

© Sekolah Tinggi Teknik Surabaya

40 7 821

S

P

Methods of a Priority Queue» 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)

Example» The following table shows a series of operations and

their effects on an initially empty priority queue P.

17

© Sekolah Tinggi Teknik Surabaya

Operation Output Priority QueueinsertItem(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 {}

Implementing Priority Queue» Node Class» Icomparable ADT

18

© Sekolah Tinggi Teknik Surabaya

Node Class

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;}

Comparator ADT

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, i = 0 if a = b, and i > 0 if a > b; an error occurs if a and b cannot be compared.

PQ with a unsorted sequence» 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

PQ Sorted Example» 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

4,4 0,0 7,7 8,82,21,1

P

PQ with a sorted sequence» 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

PQ Sorted Example» 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

4,40,0 7,7 8,82,21,1

P

6,6

Comparing the Two Implementations

Method Unsorted S Sorted Ssize, isEmpty fast fastinsertItem fast O(n)minElement, minKey, removeMin O(n) fast

25

© Sekolah Tinggi Teknik Surabaya

» Assume that the size of the sequence is n.

26Microsoft

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

Student Employee

Graduate Staff Faculty

27Microsoft

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

28Microsoft

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() { … }}

29Microsoft

All classes inherit from System.Object

St r i ng Ar r ay Val ueType Except i on Del egat e Cl ass1

Mul t i castDel egat e

Cl ass2

Cl ass3

Obj ect

Enum1

St r uct ur e1EnumPr i mi t i ve t ypes

Bool ean

Byt e

I nt 16

I nt 32

I nt 64

Char

Si ngl e

Doubl e

Deci mal

Dat eTi me

System-defined types

User-defined types

Del egat e1

Ti meSpan

Gui d

30Microsoft

Part 4

• Interfaces…

31Microsoft

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}

32Microsoft

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, …

33Microsoft

.NET is heavily influenced by interfaces

• IComparable• ICloneable• IDisposable• IEnumerable & IEnumerator• IList• ISerializable• IDBConnection, IDBCommand, IDataReader• etc.

34Microsoft

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);}

35Microsoft

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 class

interface

Student

Person

36Microsoft

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