vendredi 1 mai 2015

Want to check logic on recursive calling. Would like professional opinion with strings specifically

I wanted to to know if someone could take the time out to walk me through my recursive code. I am going to explain it how I make sense of it; however, I do not think I am stepping through the code correctly. I am going to try and explain it how i interpret recursion.

  1. if( first > last ) return -1
  2. else
  3. if( result == 0 ) return last
  4. else return SeqSearch ( data,first,last-1,key )
  5. shoot back to the top of method(start all over) and check last - 1 ("keller")
  6. repeat code
  7. else return SeqSearch(data,first,last-1,key)
  8. shoot back to the top of method(start all over) check last-1("six")
  9. ect...
public static void main (String[] args)
    {
        String[] data = new String[]{"help","jackson","six","keller","mean"};
        int first = 0;
        int last = data.length-1;
        String key ="help";
        System.out.println(SeqSearch(data,first,last,key));
    }
    public static int SeqSearch(String[] data,int first,int last,String key)
    {
        if(first > last)
            return -1;
        else{
            int result = data[last].compareTo(key);
            if(result == 0)
                return last;
            else 
                return SeqSearch(data,first,last-1,key);
        }
    }   
}

Aucun commentaire:

Enregistrer un commentaire