Implementation

Write a pseudocode function called RecursiveFind, which is a recursive
implementation of the function Find: it should take the same inputs as Find in addition to another integer i, and return the same integer as Find.

1
2
3
4
5
function Find(key,B,M,j)
    for 0 <= i < M
        if(B[i] == key):
            return j + 2*i
    return -1


This function takes an array B, its length M, a non-negative integer key, and a nonnegative integer j as inputs, and returns an integer.

I want to write recursive function for the above function, i have tried this: Please check my recursive function is correct. thanks

1
2
3
4
5
6
7
RecursiveFind(key, B, M, j, i):
    if(M == 0)
         return -1
    if(B[i-1] == key)
        return True
    return RecursiveFind(B, M-1, key, j)
end function

Last edited on
return the same integer as Find.
instead of true. Rather than M-1 you need to pass i + 1 on line 6.
L1 RecursiveFind() takes 5 arguments. L6 it is called with only 4.

Perhaps:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>

int FindI(int key, const int B[], int M, int j) {
	for (int i = 0; i < M; ++i)
		if (B[i] == key)
			return j + 2 * i;

	return -1;
}

int FindR(int key, const int B[], int M, int j) {
	if (M < 0)
		return M;

	if (B[M - 1] == key)
		return j + 2 * (M - 1);

	return FindR(key, B, M - 1, j);
}

int main()
{
	const int arr[] {1, 2, 3, 4, 5};

	std::cout << FindI(2, arr, 5, 4) << '\n';
	std::cout << FindI(6, arr, 5, 4) << '\n';
	std::cout << FindR(2, arr, 5, 4) << '\n';
	std::cout << FindR(6, arr, 5, 4) << '\n';
}



6
-1
6
-1

Last edited on
@coder777 you mean that return RecursiveFind(B, M, key, j, i+1) and instead return true, return j+2*i ?
you mean that return RecursiveFind(B, M, key, j, i+1) and instead return true, return j+2*i ?
Yes, that's what I read from the requirements. Then you need to compare M against i not 0
@coder777
Thanks for the help.
@seeplus
thanks for the help
Topic archived. No new replies allowed.