We first set up an array of integers for testing:
isttosort[1]:=7;
listtosort[2]:=5;
listtosort[3]:=3;
And so on to 10.
The insertion sort algorithm is described in various places: animation; Wikipedia; code in C.
The algorithm starts at the second item in the array and compares this with the item to its immediate left (index minus 1). A temporary variable is set to the current item ([i]) and then items to the left of the current item are scanned to see if they are greater than that value. As long as the numbers to the left are greater than the temporary value they will be moved up the array. When a value is found that is not greater than the current (temporary) value or the counter (j) becomes 1 the process stops and the temporary value is inserted at the current location pointed to by j.
procedure TForm2.Button1Click(Sender: TObject);
var i,j,temp:integer;
sortedstring:string;
begin
for i:= 2 to size do
begin
temp:=listtosort[i];
j:=i;
while (j>1) and (listtosort[j-1] > temp) do
begin
listtosort[j]:=listtosort[j-1];
dec(j);
end;
listtosort[j]:=temp;
end;
It remains only to display the sorted array. Note that while in C and C++ array indexing begins at 0 in Pascal it begins at 1 so the for loop is from 2 to size and the the Boolean operation in the while loop is (j>1), not (j>0) as it is in the C/C++ code.
If the array contains 7, 3, 5, 4, 2 the sort proceeds as follows:
loop for i := 2 to 5
temp := array[i] (= 3)
j := i (2)
j > 1 and array[j-1] = 7 so is > 3
7 is copied from array[1] to array[2]
j decremented
j now = 1 so not > 1, so while loop terminates
array[j] := temp = 3 so array is now 3, 7, 5, 4, 2
i moves to 3 so temp is array[3] = 5 and j = i = 3
7 and 5 are compared, 7 > 5 so is moved up to array[3]
3 < 5 so process stops and 5 is inserted into array [2]. Array is now 3,
5, 7, 4, 2
When 4 is processed 5 and 7 will move up and 4 will be inserted into array[2]
giving 3, 4, 5, 7, 2
When 2 is processed 3, 4, 5 and 7 will move up and 2 will be inserted into
array[1] giving 2, 3, 4, 5, 7