Reputation: 31
I don't know what to put for the if statement, I am working on this for class and am still EXTREMELY new to the language. It needs to recursively return true if element x is a member of an array A[] and false if not.
public static Boolean member (int x, int A[])
{
if ( )//base case
return true;
else // general case
{
int[] T= new int [A.length-1];
for (int i=1; I<A.length; i++)
T[i-1]=A[i];
return false;
}
}
Upvotes: 1
Views: 317
Reputation: 4434
Here is another way of doing it: I tried to respect your initial code flow
public static Boolean member (int x, int A[])
{
if ( x == A[0] )//base case
return true;
else // general case
{
if (A.length == 1) {
return false;
}
int B[] = new int[A.length-1];
System.arraycopy(A, 1, B, 0, B.length);
return member(x, B);
}
}
A test example
public static void main(String[] args) {
int A[] = {5,6,7,8,11,25,135,256,1875,1254};
boolean membershipOf25 = member(25,A);
System.out.println("Is 25 member? " + membershipOf25);
boolean membershipOf256 = member(256,A);
System.out.println("Is 256 member? " + membershipOf256);
boolean membershipOf109 = member(109,A);
System.out.println("Is 109 member? " + membershipOf109);
}
The result:
Is 25 member? true
Is 256 member? true
Is 109 member? false
Upvotes: 0
Reputation: 17616
Made a project and this works.
package recursiveTest;
public class test {
public static void main(String[] args) {
// TODO Auto-generated method stub
int [] test = new int[10];
for(int i = 0; i < 10; i++){
test[i] = i;
}
System.out.println(member(4, test));
}
public static Boolean member (int x, int A[])
{
Boolean res = false;
if(A.length > 0){
if(A[0] != x){
int [] A_NEW = CreateANew(A);
res = member(x, A_NEW);
}else{
res = true;
}
}
return res;
}
public static int[] CreateANew(int A[]){
int [] A_NEW = new int [A.length-1];
for(int i = 1; i < A.length; i++){
A_NEW[i-1] = A[i];
}
return A_NEW;
}
}
Upvotes: 0
Reputation: 39457
Say you have this function/method: search(array a, int x, int index)
(1) check if index == a.length
, if yes - return false;
(2) check if x
is equal to the element a[index]
, if yes - return true;
(3) otherwise call and return search(a, x, index + 1)
This the pseude-code, you just need to write it in Java.
The function search
is recursive.
Upvotes: 1