2 Replies Latest reply: Mar 4, 2010 1:23 PM by 843853 RSS

    Recursive question...Tell me if i'm wrong....

    843853
      I had a question on an exam I just took.

      Create a recursive method that has two parameters....an array, and a value. The method return a boolean.

      the method is to search the array to return whether the value exists in the array.



      I don't think its possible without modifying the array or adding extra parameters. What do you think?
        • 1. Re: Recursive question...Tell me if i'm wrong....
          796262
          It's possible.

          What makes you say it isn't?
          • 2. Re: Recursive question...Tell me if i'm wrong....
            843853
            I just figured it out. Took me a while. I'm pissed though cause it was a long exam and this one really needed some thinking. its so simple once you realiz you have to copy the damn array into another
            public class SearchArray
            {
            
            
            
                 public static void main(String[] args)
                 {
                        final int[] array = {5,4,7,8,9,10,13,12};
                        final int value = 333;
            
                        System.out.println("Found = "+isElement(array, value));
                        System.out.println("Original Array's length is still "+array.length);
                    }
            
            
            
            
            
            
            
            
            
                 public static boolean isElement(int[] array, int value)
                 {
            
            
                        int[] myNewArray = new int[array.length-1];
            
            
            
                        /* EXPLANATION
                         * 
                         *
                         * If the value at the end of the array is what we are looking for, we are done
                         * 
                         * If it isn't the value we are looking for, and we haven't finished minimizing the
                         * array, shrink the array a value and continue searching.
                         * 
                         * 
                         * If we got to the end of the minimized array, it ain't there dude
                         */
            
                        if(array[array.length-1] == value)
                            return true;
                          
                        
                        else if (array.length != 1)
                            {
                                System.arraycopy(array, 0, myNewArray, 0, array.length-1);
                                return isElement(myNewArray, value);
                            }
                        else
                            return false;
                      
            
                    }//end isElement Method
            }//end class