23.11.2014 Views

Data Structures and Algorithms in Java[1].pdf - Fulvio Frisone

Data Structures and Algorithms in Java[1].pdf - Fulvio Frisone

Data Structures and Algorithms in Java[1].pdf - Fulvio Frisone

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Code Fragment 8.5: Algorithm<br />

PriorityQueueSort. Note that the elements of the<br />

<strong>in</strong>put sequence S serve as keys of the priority queue P.<br />

8.2 Implement<strong>in</strong>g a Priority Queue with a List<br />

In this section, we show how to implement a priority queue by stor<strong>in</strong>g its entries <strong>in</strong> a<br />

list S. (See Chapter 6.2.) We provide two realizations, depend<strong>in</strong>g on whether or not<br />

we keep the entries <strong>in</strong> S sorted by key. When analyz<strong>in</strong>g the runn<strong>in</strong>g time of the<br />

methods of a priority queue implemented with a list, we will assume that a<br />

comparison of two keys takes O(1) time.<br />

8.2.1 Implementation with an Unsorted List<br />

As our first implementation of a priority queue P, let us consider stor<strong>in</strong>g the entries<br />

of P <strong>in</strong> a list S, where S is implemented with a doubly l<strong>in</strong>ked list. Thus, the elements<br />

of S are entries (k,x), where k is the key <strong>and</strong> x is the value.<br />

Fast Insertions <strong>and</strong> Slow Removals<br />

A simple way of perform<strong>in</strong>g operation <strong>in</strong>sert(k,x) on P is to create a new entry<br />

object e = (k,x) <strong>and</strong> add it at the end of list S, by execut<strong>in</strong>g method addLast(e)<br />

on S. This implementation of method <strong>in</strong>sert takes O(1) time.<br />

The above <strong>in</strong>sertion algorithm implies that S will be unsorted, for always <strong>in</strong>sert<strong>in</strong>g<br />

entries at the end of S does not take <strong>in</strong>to account the order<strong>in</strong>g of the keys. As a<br />

consequence, to perform operation m<strong>in</strong> or removeM<strong>in</strong> on P, we must <strong>in</strong>spect all<br />

the elements of list S to f<strong>in</strong>d an entry (k, x) of S with m<strong>in</strong>imum k. Thus, methods<br />

m<strong>in</strong> <strong>and</strong> removeM<strong>in</strong> take O(n) time each, where n is the number of entries <strong>in</strong> P<br />

460

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!