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);
}
Binsearch := Binsearch(...);instead of justBinsearch(...);? (Same for the C version btw.) Otherwise it might not return a value in that case. - stakx - no longer contributing