1) Write a Java pseudocode that uses recursion to accomplish the task. Here is a hint. When you are searching for a particular value in an array, there are two possible outcomes.
a. The value is found and the array index of that value is returned.
b. The value is not found and we return -1.
2) Convert the pseudocode in (1) above into a working Java program.
If you need any correction/clarifications kindly comment
Please give a Thumps Up if you like the answer.
PseudoCode
Main
Step 1: Start
Step 2:Declare and initialize input array.
Step 3: Declare and initialize the search key.
Step 4: Call the recursive function index=recSearch(a, 0, a.length-1, key)
Step 5:If index!=1, then the value is found . Otherwise, The value is not found .
Step 6: Stop
Function
recSearch(int arr[], int l, int r, int x)
Step 1: if (r <
l) return -1
Step 2: if (arr[l] == x)
return l
Step 3: if (arr[r] ==
x) return r
Step 4: Otherwise call
recursive function recSearch(arr, l+1, r-1, x);
Step 5: Stop
Program
import java.util.Scanner;
public class Main
{
public static void main(String args[])
{
int i,key=9;
int
a[]={1,4,7,9,10};
int index = recSearch(a, 0,
a.length-1, key);
if (index != -1)
System.out.println("Element " + key + " is present at index "
+
index);
else
System.out.println("Element " + key + " is not present");
}
public static int recSearch(int arr[], int l, int r, int x)
{
if (r <
l)
return -1;
if (arr[l]
== x)
return l;
if (arr[r]
== x)
return r;
return
recSearch(arr, l+1, r-1, x);
}
}
Output
Element 9 is present at index 3
Get Answers For Free
Most questions answered within 1 hours.