首页 文章

检查数组是否在java中递归排序

提问于
浏览
1

我想编写一个名为 itisSorted 的方法(返回一个布尔值),它接受两个参数;

  • data :整数数组

  • n :数组中的元素数

并递归检查数组是否已排序 . 也就是说,如果(且仅当) data 数组被排序,则返回 true .

public boolean itisSorted(int [] data, int n)
{
  if(data.length ==0 || data.length==1) 
  return true;
  else if (data[n] > data[n-1]) //here i compare the first two elements 
  return false;
   else //here is where i put the recursive call to check if 
    // the rest of the array is sorted, but I am having difficulties with the 
    // part of the code
}

4 回答

  • 1

    我想你想要这样的东西

    public static boolean itisSorted(int[] data, int n) {
      // Null or less then 2 elements is sorted.
      if (data == null || n < 2) {
        return true;
      } else if (data[n - 2] > data[n - 1]) {
        // If the element before (n-2) this one (n-1) is greater,
        return false;
      }
      // recurse.
      return itisSorted(data, n - 1);
    }
    
    public static void main(String[] args) {
      int [] data = {1,2,3};
      System.out.println(Arrays.toString(data) //
          + (itisSorted(data, data.length) ? " Sorted" : " Unsorted"));
      data = new int[] {3,2,1};
      System.out.println(Arrays.toString(data) //
          + (itisSorted(data, data.length) ? " Sorted" : " Unsorted"));
    }
    
  • 0

    使用递归的解决方案

    int isArraySorted(int []a, int index)
    {
        if(index == 1 || a.length == 1)
            return 1;
        return (a[index -1] <= a[index-2]) ? 0 : isArraySorted(a, index-1) ;
    }
    

    相应地改变下降的条件 .

  • 3

    //使用此方法无需传递数组的长度

    public static boolean isOrdered(int nums[])
    {
        // Base Cases
        if (nums.length == 0)
            return true;
        if (nums.length == 1)
            return true;
    
        int[] temp = new int[nums.length - 1];
    
        if (nums[0] <= nums[1]) {
            for (int i = 1; i < nums.length; i++) {
                temp[i-1] = nums[i];
            }
            return isSorted(temp);
        } else 
            return false;
    
    }
    
  • 1
    public boolean itisSorted(int [] data, int n)
    {
    if(data.length ==0 || data.length==1) 
      return true;
    else if (data[n] > data[n-1]) //here i compare the first two elements 
      return false;
     else
     {
      if(n==data.length-1)
      {
          return true;
      }
      return itisSorted(data, n+1); //recursion, checks next integer in the array
     }
    

    这是你想要的答案吗?

相关问题