0

Given an array of integers f, I want to see if f[k]=k for some k in the array. I'm having some trouble because I would like to return on the left and right half of the array, but I am not sure how to go about doing that. This is what I have so far:

public class Find {

    int a = 0;

    public boolean find(int[] f) {
        if(f.length < 1) {
            return false;
        }
        System.out.println(f[0] + " " + a);
        if(f.length == 1 && f[0] == a) {
            return true;
        }
        if(f.length == 1 && f[0] != a) {
            return false;
        }

        int[] L = Arrays.copyOfRange(f, 0, f.length / 2);
        int[] R = Arrays.copyOfRange(f, f.length / 2, f.length);
        find(L);
        a++;
        //find(R);

        return find(R); //only finds in the right half...
    }


    public static void main(String[] args) {
        Find F = new Find();
        int[] test = {0, 13, 2, 3, 4};
        System.out.println(F.find(test));
    }
}
3
  • I'm worried that you're not passing in what it is that you're searching to the method, but rather keeping it as a field. It'll work like that (assuming one's code is correct), but you'll have to reassign a every time on the object instead of changing your method call. Commented May 11, 2014 at 2:28
  • @Makoto: Could you elaborate? I don't quite understand what you are getting at. Commented May 11, 2014 at 2:30
  • Sure. Instead of having a as a field, add it as a parameter to your method instead, so your signature to find would be public boolean find(int[] data, int value). This way, you could just call the method with whichever value you wanted (e.g. find(test, 2)). Actually, the way it's written now, it'll always be finding 0 - that may not be correct depending on your test data. You're definitely going to want to fix that. Commented May 11, 2014 at 2:32

1 Answer 1

1

You could do the following, you currently search the left side but do not return the result:

return find(R) || find(L);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.