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):
If you are looking for an example of insertion sort to test I placed the above code into the small program below:
This is an implementation of the sorting algorithm that you have posted above. There are only 2 major differences here:
Var numbers : array[1..5] of Integer;
so that we can easily test this.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.