Java:递归查找列表中的最小元素

时间:2013-03-27 02:25:07

标签: java list recursion minimum

我将在前面说这是作业。我只是在寻找一些指针。我一直用这个来绞尽脑汁,而对于我的生活,我只是没有得到它。我们被要求在列表中找到最小元素。我知道我需要一个子列表,但在那之后我不确定。任何指针都会很棒。感谢。

/** 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());

5 个答案:

答案 0 :(得分:3)

递归算法的要点是必须计算的所有内容都是通过返回值或其他参数完成的。你不应该在递归步骤的本地调用之外有任何东西。

由于你必须找到最小元素,你应该考虑一下:

  • 由一个元素组成的列表的min元素是该元素
  • 通用列表的min元素是第一个元素与剩余列表的最小值之间的最小值

通过考虑这些因素,它应该易于实施。特别是因为递归算法具有与其算法描述非常相似的便利性。

答案 1 :(得分:1)

您需要找到应用于列表的函数min与应用于子列表的函数min之间的关系。

min([a b c d e ...])= f(a,min([b c d e ...]))

现在你只需要找到函数f。一旦你有了这段关系,那么实施它很容易。祝你好运。

答案 2 :(得分:0)

在最一般意义上,递归是一个基于分解工作的概念,然后将较小的工作块委托给自己的副本。要使递归工作,您需要三件事:

  1. 工作分解。你如何使每一步“更简单”?
  2. 递归调用。在某些时候,你的功能必须调用自己,但是“工作”更少。
  3. 基本情况。什么是停止递归过程的(通常是微不足道的)结束案例?
  4. 在您的情况下,您正在尝试创建一个在列表上运行的函数min。你认为通过每次缩小一个列表(第一个元素的子列表)可以以某种方式减少(分解)你的工作是正确的。正如其他人所提到的那样,我们的想法是检查第一个元素(你刚刚取消)与“列表的其余部分”。那么这里是信仰的飞跃。此时,您可以“假设”您的min函数将在子列表上工作,并且只在子列表上进行函数调用(递归调用)。现在你必须确保你的所有电话都会返回(即确保它不会永远递归)。这就是你的基础案例的来源。如果你的列表大小为1,那么唯一的元素就是列表中最小的元素。无需再次致电min,只需返回(您在原始帖子中已有的部分)。

答案 3 :(得分:0)

你去,在方法中试试这个:

    public static Integer minimum(List<Integer> t) {
        int minInt;
       if (t.size() == 1) {
        return t.get(0);
       } else {
            int first = t.get(0);
            List<Integer> u = t.subList(1, t.size());
            minInt = Math.min(first, u.get(0));
            minInt = IntegerList.minimum(u);
          }
         return minInt;
      }

希望这可以解决您的问题。

答案 4 :(得分:0)

/**
 * The function computes the minimum item of m (-1 if m is empty). 
 * @param m: The MyList we want to compute its minimum item.
 * @return: The minimum item of MyList    
 */ 
public int minimum(MyList<Integer> m){

    int res = 0;
    int e0 = 0;
    int e1 = 0;

    // Scenarios Identification
    int scenario = 0;

    // Type 1. MyLyst is empty
    if(m.length() == 0) {
        scenario = 1;
    }else {
    // Type 2. MyLyst is not empty
        scenario = 2;
    }

    // Scenario Implementation
    switch(scenario) {

    // If MyLyst is empty
    case 1:
        res = -1;
        break;
        // If there is 1 or more elements   
    case 2:
        //1. Get and store first element of array
        e0 = m.getElement(0);
        //2. We remove the first element from MyList we just checked
        m.removeElement(0);
        //3. We recursively solve the smaller problem
        e1 = minimum(m); 
        //4. Compare and store results
        if(e0 < e1) {
            res = e0;
        }
        else {
            res = e1;
        }
        //5. Return removed element back to the array
        m.addElement(0, e0);
        break;
    }
    //6. Return result 
    return res;
}