booleanpascallong-integerbubble-sortinsertion-sort

Got "Boolean" expected "LongInt" pascal


I get this error on my insertion sort algorithm:

insertionsort.lpr(19,17) Error: Incompatible types: got "Boolean" expected "LongInt"

Here's the line 19 of my code

 while j > 0 and A[j]>key do            

I have tried googling all over the internet but i couldn't find any syntax errors or anything.

Here's the full code if it helps :

program instert;
uses crt;
const
  N = 5;
var
   i:integer;
   j:integer;
   key:integer;
   A : Array[1..N] of Integer;


procedure insertionsort;
  begin
  for i := 2 to N  do
    begin
    key := A[1];
    j:= i - 1;
        while j > 0 and A[j]>key do
        begin
          A[j+1] := A[j] ;
          j := j-1;
        end;
    A[j+1] := key ;
   end;
 end;

begin
  A[1]:= 9;
  A[2]:= 6;
  A[3]:= 7;
  A[4]:= 1;
  A[5]:= 2;
  insertionsort;
end.

I also get the same error on the bubble sort algorithm i did. Here's the error line

bubblesort.lpr(26,14) Error: Incompatible types: got "Boolean" expected "LongInt"

Here's line 26 of my algorithm:

 until flag = false or N = 1 ;   

Here's the full code:

program bubblesort;
uses crt;

var
  flag:boolean;
  count:integer;
  temp:integer;
  N:integer;
  A : Array[1..N] of Integer;

procedure bubblesort ;
begin
  Repeat
    flag:=false;
    for count:=1 to (N-1)  do
    begin
    if A[count] > A[count + 1] then
       begin
       temp := A[count];
       A[count] := A[count + 1];
       A[count] := temp;
       flag := true;
       end;
    end;
    N := N - 1;
  until flag = false or N = 1 ;
end;

begin
  A[1]:= 9;
  A[2]:= 6;
  A[3]:= 7;
  A[4]:= 1;
  A[5]:= 2;
  N := 5;
  bubblesort;
end.

Solution

  • In Pascal, boolean operators and and or have higher precedence than the comparison operators >, =, etc. So in the expression:

    while j > 0 and A[j] > key do
    

    Given that and has higher precedence, Pascal sees this as:

    while (j > (0 and A[j])) > key do
    

    0 and A[j] are evaluated as a bitwise and (since the arguments are integers) resulting in an integer. Then the comparison, j > (0 and A[j]) is evaluated as a boolean result, leaving a check of that with > key, which is boolean > longint. You then get the error that a longint is expected instead of the boolean for the arithmetic comparison.

    The way to fix it is to parenthesize:

    while (j > 0) and (A[j] > key) do ...
    

    The same issue applies with this statement:

    until flag = false or N = 1 ;
    

    which yields an error because or is higher precedence than =. So you can parenthesize:

    until (flag = false) or (N = 1);
    

    Or, more canonical for booleans:

    until not flag or (N = 1);    // NOTE: 'not' is higher precedence than 'or'
    

    When in doubt about the precedence of operators, parenthesizing is a good idea, as it removes the doubt about what order operations are going to occur.