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 53<br />

2.2.1 Sorting by Straight Insertion<br />

This method is widely used by card players. The items (cards) are conceptually divided into a<br />

destination sequence a 0 ... a i-1 <strong>and</strong> a source sequence a i ... a n-1 . In each step, starting with i = 1 <strong>and</strong><br />

incrementing i by unity, the ith element of the source sequence is picked <strong>and</strong> transferred into the destination<br />

sequence by inserting it at the appropriate place. The process of sorting by insertion is shown in an<br />

example of eight numbers chosen at r<strong>and</strong>om (see Table 2.1).<br />

Initial keys 44 55 12 42 94 18 06 67<br />

i=1 44 55 12 42 94 18 06 67<br />

i=2 12 44 55 42 94 18 06 67<br />

i=3 12 42 44 55 94 18 06 67<br />

i=4 12 42 44 55 94 18 06 67<br />

i=5 12 18 42 44 55 94 06 67<br />

i=6 06 12 18 42 44 55 94 67<br />

i=7 06 12 18 42 44 55 67 94<br />

Table 2.1. A Sample Process of Straight Insertion Sorting.<br />

The algorithm of straight insertion is<br />

FOR i := 1 TO n-1 DO<br />

x := a[i];<br />

insert x at the appropriate place in a 0 ... a i-1<br />

END<br />

In the process of actually finding the appropriate place, it is convenient to alternate between<br />

comparisons <strong>and</strong> moves, i.e., to let x sift down by comparing x with the next item a j , <strong>and</strong> either inserting x<br />

or moving a j to the right <strong>and</strong> proceeding to the left. We note that there are two distinct conditions that may<br />

cause the termination of the sifting down process:<br />

1. An item a j is found with a key less than the key of x.<br />

2. The left end of the destination sequence is reached.<br />

PROCEDURE StraightInsertion; (* ADenS2_Sorts *)<br />

VAR i, j: INTEGER; x: Item;<br />

BEGIN<br />

FOR i := 1 TO n-1 DO<br />

x := a[i]; j := i;<br />

WHILE (j > 0) & (x < a[j-1]) DO<br />

a[j] := a[j-1]; DEC(j)<br />

END;<br />

a[j] := x<br />

END<br />

END StraightInsertion<br />

Analysis of straight insertion. The number C i of key comparisons in the i-th sift is at most i-1, at least<br />

1, <strong>and</strong> — assuming that all permutations of the n keys are equally probable — i/2 in the average. The<br />

number M i of moves (assignments of items) is C i + 1. ). Therefore, the total numbers of comparisons <strong>and</strong>

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

Saved successfully!

Ooh no, something went wrong!