25.11.2014 Views

Algorithms and Data Structures

Algorithms and Data Structures

Algorithms and Data Structures

SHOW MORE
SHOW LESS

Create successful ePaper yourself

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

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

moves are<br />

C min = n - 1 M min = 2*(n - 1)<br />

C ave = (n 2 - n)/4 M ave = (n 2 + 3n - 4)/4<br />

C max = (n 2 - 3n + 2)/2<br />

M max = (n 2 - n)/2<br />

The minimal numbers occur if the items are initially in order; the worst case occurs if the items are initially in<br />

reverse order. In this sense, sorting by insertion exhibits a truly natural behavior. It is plain that the given<br />

algorithm also describes a stable sorting process: it leaves the order of items with equal keys unchanged.<br />

The algorithm of straight insertion is easily improved by noting that the destination sequence a 0 ... a i-1 ,<br />

in which the new item has to be inserted, is already ordered. Therefore, a faster method of determining the<br />

insertion point can be used. The obvious choice is a binary search that samples the destination sequence in<br />

the middle <strong>and</strong> continues bisecting until the insertion point is found. The modified sorting algorithm is called<br />

binary insertion.<br />

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

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

BEGIN<br />

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

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

WHILE L < R DO<br />

m := (L+R) DIV 2;<br />

IF a[m]

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

Saved successfully!

Ooh no, something went wrong!