Insertion Sort in pascal

Asked

Viewed 340 times

0

I have to implement the ordering method Insertion Sort in Pascal.

The problem is that in my algorithm I’m having to do several ifs. One for each possibility.

I wonder if there is a better method to do this.

My code:

Program insertion_sort ;
var
    cont , aux : integer ;
    numero : array[1..5] of integer ;  
Begin
    for cont := 1 to 5 do
        begin
            writeln('Digite um numero : ');
            read(numero[cont]);
        end;

    for cont := 1 to 5 do
        begin
            if(numero[1] > numero[2]) then
                begin
                    aux := numero[1] ;
                    numero[1] := numero[2] ;
                    numero[2] := aux;
                end;
            writeln(numero[cont]);
        end;
End.
  • 2

    Young man, do not use external sources to post your code. If you paste it in the question, select the code text and click Ctrl + K it will get formatted.

  • I didn’t know I couldn’t , but vlw

1 answer

0

The solution was given in the English version:

https://stackoverflow.com/questions/28135957/how-to-use-insertion-sort-in-an-array-with-pascal

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;

In the link there is an example of how to use.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.