0
votes

I seem to have a problem with a function in Pascal. The program is just an ordinary recursive binsearch, but it returns always the value of 4? Can anybody point to the mistake in the solution?

var i: integer;
const n = 10;
type tablice = array[1..n] of integer;

function Binsearch(const tab:tablice;l:integer;p:integer;x:integer):integer;
var s: integer;
begin
  if l=p then 
  begin
    if tab[l]=x then 
      Binsearch:=p
    else 
      Binsearch:=-1;
    end
    else 
    begin
      s:=(l+p) div 2;
      if tab[s]<x then 
        l:=s+1
      else 
        p:=s;
      Binsearch(tab,l,p,x);
    end;
end;

var A:tablice;
    x:integer;


begin
  for i:=1 to n do A[i]:=i;

  x:=30;
  writeln(Binsearch(A,1,n,x));
  readln;

end.

On the other hand same code in C++ works fine:

using namespace std;

int rekursja(int tab[], int l, int p, int x){
    if(l==p){
        if(tab[l]==x) return l;
        else return -1;
    }else{
        int s=(l+p)/2;
        if(tab[s]<x) l=s+1;
        else p=s;
        rekursja(tab,l,p,x);
    }
}

int main(){
    int t[] = {1,2,3,4,5,6,7,8,9,11};
    cout << rekursja(t,0,9,11);
}
1
Shouldn't it be Binsearch := Binsearch(...); instead of just Binsearch(...);? (Same for the C version btw.) Otherwise it might not return a value in that case. - stakx - no longer contributing
First of all, you never returned a result in the pascal code.. It should be Result := -1; exit; Div is not the same as dividing.. In other words, div is not the same as / operator. Div will divide and then round the result guaranteeing that the result of the division is an integer and not a float. Your c++ code will do the division and chop off the decimals. Your pascal code will do the division and round the result closer to zero.. - Brandon
Ok. Found what's been wrong. Turns out what stakx wrote was the whole point of the problem. Thanks. - user3142434
@CantChooseUsernames: that's all wrong - BeniBela
If you would enable compiler warnings then the compiler would have found the problem for you - David Heffernan

1 Answers

1
votes

Binsearch returns the result only exiting from the last call (result := -1 in this case). In the other cases no result is assigned, so a random value is shown.

Change the ricorsive call with

Binsearch:=Binsearch(tab,l,p,x);

In this way it returns the result to all previos call.