25.11.2014 Views

Algorithms and Data Structures

Algorithms and Data Structures

Algorithms and Data Structures

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

N.Wirth. <strong>Algorithms</strong> <strong>and</strong> <strong>Data</strong> <strong>Structures</strong>. Oberon version 140<br />

7 w3<br />

1<br />

5<br />

5<br />

12<br />

NIL<br />

w2<br />

w1<br />

Fig. 4.10. Insertion in ordered list<br />

Referring to Fig. 4.10, we determine the condition under which the scan continues to proceed to the next<br />

element; it consists of two factors, namely,<br />

(w1 # NIL) & (w1.key < x)<br />

The resulting search procedure is:<br />

PROCEDURE search (x: INTEGER; VAR root: Word); (* ADenS432_List3 *)<br />

VAR w1, w2, w3: Word;<br />

BEGIN<br />

(*w2 # NIL*)<br />

w2 := root; w1 := w2.next;<br />

WHILE (w1 # NIL) & (w1.key < x) DO<br />

w2 := w1; w1 := w2.next<br />

END;<br />

(* (w1 = NIL) OR (w1.key >= x) *)<br />

IF (w1 = NIL) OR (w1.key > x) THEN (*new entry*)<br />

NEW(w3); w2.next := w3;<br />

w3.key := x; w3.count := 1; w3.next := w1<br />

ELSE<br />

INC(w1.count)<br />

END<br />

END search<br />

In order to speed up the search, the continuation condition of the while statement can once again be<br />

simplified by using a sentinel. This requires the initial presence of a dummy header as well as a sentinel at<br />

the tail.<br />

It is now high time to ask what gain can be expected from ordered list search. Remembering that the<br />

additional complexity incurred is small, one should not expect an overwhelming improvement.<br />

Assume that all words in the text occur with equal frequency. In this case the gain through<br />

lexicographical ordering is indeed also nil, once all words are listed, because the position of a word does<br />

not matter if only the total of all access steps is significant <strong>and</strong> if all words have the same frequency of<br />

occurrence. However, a gain is obtained whenever a new word is to be inserted. Instead of first scanning<br />

the entire list, on the average only half the list is scanned. Hence, ordered list insertion pays off only if a<br />

concordance is to be generated with many distinct words compared to their frequency of occurrence. The<br />

preceding examples are therefore suitable primarily as programming exercises rather than for practical<br />

applications.<br />

The arrangement of data in a linked list is recommended when the number of elements is relatively small

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

Saved successfully!

Ooh no, something went wrong!