I tried researching here, and on the internet in general, but since pseudocode writing is rather diverse and many use different signs for different things, I couldn't find anything that might fit my question.
Given the following: an array A (not necessarily already sorted) of the order n, and the indexes p,r so that 1<=p<=r<=n;
I am given the following recursive algorithm (in pseudocode), and I wonder what specific two lines (bolded) in it do/mean:
MAXB(A,p,r)
if p=r
then return A[p]
else temp<-----MAXB(A,p,r-1)
if temp>=A[r]
then return temp
else return A[r]
I do not exactly understand the process that is done with the 'temp'. If it changes MAXB(A,p,r)
into MAXB(A,p,r-1)
how can it be compared to the value of A[r]
at all? I know the algorithm certainly doesn't do what it is supposed to do, according to the description: return the index of the item with the highest value, between A[p]
and A[r]
- certainly doesn't do that, yet I am not sure how can the temp even be compared to any value.
It looks to me like temp
is a variable.
It's making a recursive call to your funciton: MAXB
and storing the value from that call in a variable called temp
.
It's then checking whether or not temp
is greater than or equal to A[r]
, and if it is, than it returns temp
. If it is less than A[r]
it returns A[r]
Here's an explanation of the entire function:
if p=r
then return A[p]
if p
and r
are equal, than there is only one value between A[p]
and A[r]
, and therefore, that one values is the greatest and you return that value.
else
temp<-----MAXB(A,p,r-1)
You use your own function, MAXB
to get the greatest value between A[p]
and A[r-1]
, and you store that in temp
if temp>=A[r]
then return temp
else
return A[r]
you compare to greatest value between A[p]
and A[r-1]
to A[r]
. Whichever one is greater, must be the greatest value between A[p]
and A[r]
, and is therefore the value that you want to return.