打破递归并在Java中返回布尔值

时间:2014-06-01 03:18:21

标签: java recursion

我有一个数组,我必须编写一个带有布尔返回类型的方法来检查数组的元素,看看它们是否使用递归按升序排列。我想要做的是打破递归,同时在我发现第一次违规时立即返回false。这是可能的,如果是的话怎么样?

练习告诉我必须使用递归而不是for循环。这就是我到目前为止所写的内容。

public class ProveIfSorted
{
    public static void main(String args[])
    {
        int[] myArray = new int[] {1, 3, 5, 7, 9};

        System.out.println("The array is sorted: " + checkSorted(myArray, 4);
    }

    private static boolean checkSorted(int[] array, int i)
    {
        if(i == 0)
        {
            boolean isSorted = true;
            return isSorted;
        }
        else
        {
            if(array[i] >= array[i - 1] == isSorted(int[] array, (i - 1))
            {
                return isSorted = true;
            }
            else
            {
                ?????;
            }
        }
    }
}

5 个答案:

答案 0 :(得分:0)

private boolean isSorted(int[] arr, int start) {
  if (arr.length - start < 2) 
      return True;

  if (arr[start] > arr[start+1])
      return False;

  return isSorted(arr, start+1)

}

答案 1 :(得分:0)

似乎相对简单。我将描述伪代码,因为实际代码很简单。

(先决条件:你的函数应该接受数组和两个整数(第一个,第二个)作为参数。另一个变体是有一个int参数,并在两个上下文中使用它。)

  • 对数组进行边界检查 - 如果它为零或为null,则返回false
  • 对两个int参数进行边界检查:如果第二个参数大于数组的长度,则返回true。我们已经离开阵列,没有发现任何违规行为。

  • 实际检查条件:

    • 如果数组[first]中的值小于(或等于)array [second]中的值,那么我们可以安全地继续递归;返回方法的调用,并按1递增第一和第二。
    • 否则,请返回false

答案 2 :(得分:0)

此代码将递归检查元素是否小于其上方的元素。递归部分是它将返回对自身的调用。如果元素小于下一个,则继续。如果它到达结尾,则返回true。如果元素在任何时候大于下一个元素,它将返回false,停止递归。

public static void main(String args[]){
        int[] myArray = new int[] {1, 3, 5, 3, 6};
        int[] myArray1 = new int[] {1, 3, 5, 6, 6};

        System.out.println("The array is sorted: " + checkSorted(myArray, 0));// Outputs false
        System.out.println("The array is sorted: " + checkSorted(myArray1, 0));//Outputs true
    }

    private static boolean checkSorted(int[] array, int i){
        if(i+1 < array.length){
            if(array[i] <= array[i+1]){
                return checkSorted(array, i+1);
            }else{
                return false;
            }
        }
        return true;
    }

}

答案 3 :(得分:0)

这是使用尾递归的示例。评论应该解释。这看似简单。

public class ProveIfSorted{

    public static void main( String[] args ){
        int[] myArray = new int[]{ 1, 3, 5, 5, 10, 17, 19 };
        System.out.println( "The array is sorted: " + checkSorted( myArray ) );
    }

    /**
     * This is the public entry point which should be kept as simple as possible.
     * All the caller has is the array, so that is all that should be asked.
     * The public interface should not pass the burden of setup to the caller.
     * Think of this as the wrapper or setup method for the recursive method.
     * 
     * @param array the array under test. Null or empty arrays are considered to
     *               be unsorted -- by definition.
     * @return {@code true} if the array is sorted ascending.
     */
    public static boolean checkSorted( int[] array ){
        // Now we call the recursive method -- if the array is not null. Here we
        // pass in index values and an indicator for what we have found so far.
        // At this point, all we're conserned about is if the array is null or
        // empty.
        return checkSorted( array, 1, array != null && array.length > 0 );
    }

    /**
     * This is the private work horse. Using tail recursion, we can exit if the
     * result of the previous invocation found the array to be unsorted or if we
     * have arrived at the end of the array. Otherwise, we call ourselves with
     * the next index value and the result of the comparison of this entry with
     * the previous entry.
     *
     * @param array the array under test
     * @param ndx    the array slot to examine with the previous slot
     * @param sorted the result of the last examination. As long as this is
     *                {@code true}, we continue testing.
     * @return {@code true} if the array is sorted ascending.
     */
    private static boolean checkSorted( int[] array, int ndx, boolean sorted ){
        if( !sorted || ndx == array.length ){
            return sorted;
        }
        else{
            return checkSorted( array, ndx + 1, array[ ndx - 1] <= array[ ndx] );
        }
    }
}

答案 4 :(得分:-2)

如果函数只是这样,那么当你找到你的匹配时,只需在循环中写回return false,并在循环外写结束返回true。如果函数有额外的活动来执行此检查,则在循环之前创建一个默认值为true的布尔变量,在匹配时将boolean变量设置为false并添加break语句。 E.g。

boolean Nomatch = true;
for(int i=0;i<10;i++) {
 if(i==5) {
     Nomatch = false;
     break;
 }
 }