18.10.2014 Views

Object-oriented Software in Ada 95

Object-oriented Software in Ada 95

Object-oriented Software in Ada 95

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.

202 Child libraries<br />

14.6 A generic procedure to sort data<br />

A generic sort procedure us<strong>in</strong>g the above variation of the bubble sort algorithm has the follow<strong>in</strong>g specification:<br />

generic<br />

type T is private; --Any non limited type<br />

type Vec_Range is (); --Any discrete type<br />

type Vec is array( Vec_Range ) of T;<br />

with function ">"( First, Second:<strong>in</strong> T ) return Boolean is ;<br />

procedure Sort( Items:<strong>in</strong> out Vec );<br />

The generic formal parameters for the procedure Sort are:<br />

Formal parameter<br />

type T is private;<br />

type Vec_Range is ();<br />

type Vec is array( Vec_Range ) of T;<br />

with function ">"(First,Second:<strong>in</strong> T)<br />

return Boolean is ;<br />

Description<br />

The type of data item to be sorted.<br />

The type of the <strong>in</strong>dex to the array.<br />

The type of the array to be sorted.<br />

A function that the user of the<br />

generic procedure provides to<br />

compare pairs of data items.<br />

The implementation of the generic procedure is:<br />

procedure Sort( Items:<strong>in</strong> out Vec ) is<br />

Swaps : Boolean := True;<br />

Tmp : T;<br />

beg<strong>in</strong><br />

while Swaps loop<br />

Swaps := False;<br />

for I <strong>in</strong> Items'First .. Vec_Range'Pred(Items'Last) loop<br />

if Items( I ) > Items( Vec_Range'Succ(I) ) then<br />

Swaps := True;<br />

Tmp := Items( Vec_Range'Succ(I) );<br />

Items( Vec_Range'Succ(I) ) := Items( I );<br />

Items( I ) := Tmp;<br />

end if;<br />

end loop;<br />

end loop;<br />

end Sort;<br />

Note:<br />

Passes through the data are repeated until there are no more swaps.<br />

The use of 'Succ delivers the next <strong>in</strong>dex. Remember the array might have an <strong>in</strong>dex of an enumeration<br />

type, so + cannot be used.<br />

© M A Smith - May not be reproduced without permission

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

Saved successfully!

Ooh no, something went wrong!