How to use insertion sort in an array with pascal

freepascalpascal

Can someone help me out here. I try to understand the insertion sort (in pascal). But i find it really complicated. Can someone just make me a simple code: the user types in 5 numbers(array), and then use insertion sort. This would really help me alot to understand it.

This is what i have at the moment, but i don't know if it's correct:

Procedure InsertionSort(numbers : Array of Integer; size : Integer);
Var i, j, index : Integer


Begin
 For i := 2 to size-1 do
  Begin
   index := numbers[i];
   j := i;
   While ((j > 1) AND (numbers[j-1] > index)) do
    Begin
     numbers[j] := numbers[j-1];
     j := j - 1;
    End;
   numbers[j] := index;
  End;

End.

Best Answer

Pascal-Programming.info has the following Insertion Sort algorithm as an example for pascal. The example they provide is exactly the same as your procedure line for line. (Pascal-Programming.info sort examples here):

Procedure InsertionSort(numbers : Array of Integer; size : Integer);
Var i, j, index : Integer


Begin
 For i := 2 to size-1 do
  Begin
   index := numbers[i];
   j := i;
   While ((j > 1) AND (numbers[j-1] > index)) do
    Begin
     numbers[j] := numbers[j-1];
     j := j - 1;
    End;
   numbers[j] := index;
  End;

End.

If you are looking for an example of insertion sort to test I placed the above code into the small program below:

program InsertionSort;

Var x: Integer;
Var numbers : array[1..5] of Integer;

procedure InsertionSort(size : Integer );
Var i, j, index : Integer;
Begin
   For i := 2 to size do
   Begin
      index := numbers[i];
      j := i;
      While ((j > 1) AND (numbers[j-1] > index)) do
      Begin
         numbers[j] := numbers[j-1];
         j := j - 1;
      End;
      numbers[j] := index;
   End;
End;

Begin
   writeln('Insertion Example: ');

   numbers[1] := 9001;
   numbers[2] := 42;
   numbers[3] := 32;
   numbers[4] := 64;
   numbers[5] := 2;

   for x:= 0 to 5 do
      writeln('unsorted[', x, '] = ', numbers[x] );

   InsertionSort(5);

   writeln('=== sorted ===');

   for x:= 0 to 5 do
      writeln('sorted[', x, '] = ', numbers[x] );

End.

This is an implementation of the sorting algorithm that you have posted above. There are only 2 major differences here:

  1. I no longer pass the array to be sorted in by value, instead I am using a globally defined array Var numbers : array[1..5] of Integer; so that we can easily test this.
  2. I then pass only the size of the array to the InsertionSort procedure procedure InsertionSort(size : Integer );

I have tested this code locally with Free Pascal. If you would like more information on implementing sorting, I would recommend this guide on sorting in pascal.

Related Topic