I have to a program using recursion whose input is an array A of positive numbers and a positive number x. The program should print the smallest element of A that is greater than x. If such an element does not exist, the program should print −1. For example, if A = [1, 3, 5, 3, 6, 5] and x = 3 then the program should print 5.
I have solved this program by conventional method without using recursion as follows:
FindNum(A[ ], x) {
result = -1;
for (i = 0; i < len(A[ ]); i++) {
if (A[i] > x AND (result > A[i] OR result == -1)) {
result = A[i];
}
}
print (result);
}
I have implemented this pseudo code in python accordingly and it works fine. Now I must do it using recursion. I have tried to do it but I am not so sure how to implement it correctly:
FindNum(A [ ], x) {
i = len(A[]) - 1;
result = -1;
while (i > 0 {
if (A[i] > x AND (result > A[i] OR result == -1)) {
result = A[i];
i--;
}
FindNum(A[i], x);
}
print result;
}
Python recursive function with simple conditions (without one-liners). It finds result for list tail, then tries to improve it with current element
def mingreater(A, x):
if 0 == len(A):
return -1
result = mingreater(A[1:], x)
if result > 0:
if A[0] > x:
return min(result, A[0])
else:
if A[0] > x:
return A[0]
return result
Without Python-specific slices:
def mingreater(A, x, idx):
if idx == len(A):
return -1
result = mingreater(A, x, idx + 1)
if result > 0:
if A[idx] > x:
return min(result, A[idx])
else:
if A[idx] > x:
return A[idx]
return result