Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Recursion help needed

Tags:

java

recursion

I've been asked to create a public method that does nothing but to call another method that is recursive. The purpose of the second method is to search for a Int value inside an array.

So far I have this:

int[] array = {1, 2, 3, 7, 8, 11, 20, 30, 50, 100};
int cont = 0;

public int searchI(int x) {
    searchR(x);
    return x;
}

private void searchR(int y) {
    if (cont < array.length) {
        if (array[cont] == y) {
            System.out.println(y);
        } else {
            searchR(cont++);   
        }
    }
}

However, no matter what number I use, either one in the array or not, it always prints the value of y. I'm still new to recursion and not quite grasping the essence of it yet. That's probably why my method isn't working (besides that it is wrong). Any thoughts? And probably, help to grasp the term better.

like image 441
LeinadDC Avatar asked Mar 05 '26 09:03

LeinadDC


2 Answers

As far you code, this will print y when it finds y in the array because of

if (array[cont] == y) {
     System.out.println(y);
}

And after first call of searchR(x) it is searching the value of cont instead of value of x. Change searchR(cont++) to

cont++; 
searchR(y);

If you want the position of the number you're searching use System.out.println(cont) instead of System.out.println(y).

int[] array = {1, 2, 3, 7, 8, 11, 20, 30, 50, 100};
int cont = 0;

public int searchI(int x) {
    searchR(x);
    return x;
}

private void searchR(int y) {
    if (cont < array.length) {
        if (array[cont] == y) {
            System.out.println(y); //System.out.println(cont); if you want the position as output
        } else {
            cont++;
            searchR(y);

        }
    }
}
like image 192
Shafi Avatar answered Mar 06 '26 21:03

Shafi


static final int [] array={1,6,2,7,3,9,5};
 public static void searchI(int x)
{
    System.out.println(x);
    System.out.println(searchR(x,0));
}

   private static int searchR(int x,int _index)
{
    if(_index>array.length)
        return -1;
    else if(array[_index]==x)
        return _index;
    else
        return searchR(x,++_index);
}
like image 27
kaveh.n Avatar answered Mar 06 '26 22:03

kaveh.n



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!