• Post Reply Bookmark Topic Watch Topic
  • New Topic

Need Help finding a logic error  RSS feed

 
Paul Peterson
Ranch Hand
Posts: 106
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I've been playing with some examples in a text book that were not assigned in my course.  I went through some recursion exercises this week and have a logic problem somewhere in this one.  The exercise finding the minimum value in an array.  "Write a recursive method that determines the smallest element in an array of integers.  The method should return when it receives an array of one element."

I tried converting the array to a list, comparing the first two values, removing the higher value and converting the result back to an array and passing that recursively calling the method with the new array.  The next part is where I think I have an error in my logic .  I have the method execute while the size of the list is greater than 1 then it is supposed to return the array with only 1 element.  The method functions as expected until the size reaches 2.  Then for what ever reason it is adding elements, sometimes 1 sometimes several.  On one run, the beginning array had a length of 18 and the method executed more then 131,000 times before ending.

Please let me know what I am doing wrong here.



The complete class is

I wanted to compare the runtime of the other ways I have found the minimum value in an array to a recursive method.  That is why there is so much additional code.  
 
Carey Brown
Saloon Keeper
Posts: 3329
46
Eclipse IDE Firefox Browser Java MySQL Database VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think you misinterpreted part of the requirements, the method is supposed to return an int not an int[].
You are making tons of copies of the data unnecessarily. You could pass the array and the current position in the array. This works best when you provide an overloaded method as a front end to the recursive method. Something like this:
 
Paul Peterson
Ranch Hand
Posts: 106
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you!
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!