Search code examples
javalistrecursionminimum

Java: Recursively Finding the minimum element in a list


I will preface this by saying it is homework. I am just looking for some pointers. I have been racking my brain with this one, and for the life of me i am just not getting it. We are asked to find the minimum element in a list. I know i need a sublist in here, but after that i am not sure. any pointers would be great. thanks.

/** Find the minimum element in a list.
 * 
 * @param t a list of integers
 * 
 * @return the minimum element in the list
 */ 
  public static int min(List<Integer> t) { 
  if (t.size() == 1){ 
  return t.get(0); 
  } 
  else{ 
      List<Integer> u = t.subList(1, t.size());

Solution

  • In the most general sense, recursion is a concept based on breaking down work, and then delegating the smaller chunk of work to a copy of yourself. For recursion to work, you need three main things:

    1. The breakdown of work. How are you going to make each step "simpler"?
    2. The recursive call. At some point your function must call itself, but with less "work".
    3. The base case. What is a (usually trivial) end case that will stop the recursion process?

    In your case, you're trying to create a function min that operates on a list. You're correct in thinking that you could somehow reduce (breakdown) your work by making the list one smaller each time (sublist out the first element). As others have mentioned, the idea would be to check the first element (which you just pulled off) against the "rest of the list". Well here's where the leap of faith comes in. At this point, you can "assume" that your min function will work on the sublist, and just make a function call on the sublist (the recursive call). Now you have to make sure all your calls will return (i.e. make sure it will not recurse forever). That's where your base case comes in. If your list is of size 1, the only element is the smallest of the list. No need to call min again, just return (that part you already have in your original post).