Download Introduction to Programming in Turing First Edition

Transcript
Chapter 17 : Subprograms with Array Parameters
313
Element to be deleted here
1
2
3
New last element
Original last element
Figure 17.2 Deleting an Element in an Array
Here is a program that maintains a list of names in sorted
order in an array. This program does not save the list of names
between executions. It also does not check the number of names
in the list compared to the maximum array size.
% The "SortedList" program
% Maintains a sorted list of names
% Add a name to the sorted list in the correct position
procedure AddName (name : string, var list : array 1 .. * of string (*),
var listSize : int)
% The array index where the name should be placed
var insertPoint : int := 1
% Determine the location in the array where the name should be
% placed
loop
exit when insertPoint > listSize or list (insertPoint ) > name
insertPoint := insertPoint + 1
end loop
% Shift the remaining items over to make room at insertPoint
for decreasing i : listSize .. insertPoint
list (i + 1) := list (i )
end for