Check if an array is sorted, return true or false

前端 未结 13 1928
隐瞒了意图╮
隐瞒了意图╮ 2020-11-30 06:03

I am writing an easy program the just returns true if an array is sorted else false and I keep getting an exception in eclipse and I just can\'t figure out why. I was wonder

相关标签:
13条回答
  • 2020-11-30 06:29

    You shouldn't use a[i+1] because that value may or may not go off the array.

    For example:

    A = {1, 2, 3}
    // A.length is 3.
    for(i = 0; i < a.length; i ++) // A goes up to 3, so A[i+1] = A[4]
    

    To fix this, simply stop the loop one early.

    int i;
    for(i = 0; i < a.length - 1; i ++);{
    
        if (a[i] < a[i+1]) {
    
            return true;
        }else{
            return false;
    
        }
    
    }
    
    0 讨论(0)
  • 2020-11-30 06:29

    Array.prototype.every

    The every() method tests whether all elements in the array pass the test implemented by the provided function.

    arr.every(function (a, b) {
      return a > b;
    });
    
    var arr = [1,2,3] // true
    
    var arr = [3,2,1] // false
    
    0 讨论(0)
  • 2020-11-30 06:31

    For anyone using Java 8 and above, here's a simple one-liner:

    public static boolean isSorted(int[] array) {
        return IntStream.range(0, array.length - 1).noneMatch(i -> array[i] > array[i + 1]);
    }
    

    Or a logically-equivalent alternative:

    public static boolean isSorted(int[] array) {
        return IntStream.range(0, array.length - 1).allMatch(i -> array[i] <= array[i + 1]);
    }
    
    0 讨论(0)
  • 2020-11-30 06:32
    bool checkSorted(int a[], int n) {
      for (int i = 1; i < n-1; i++) {
        if (a[i] > a[i-1]) {
          return false;
        }
      }
      return true;
    }
    
    0 讨论(0)
  • 2020-11-30 06:33
    public static boolean isSorted(int[] a)
    {  
        for ( int i = 0; i < a.length - 1 ; i++ ) {
            if ( a[i] > a[i+1] )
              return false;
        }
        return true;
    }
    

    This function checks whether the array is in Ascending order or not.

    0 讨论(0)
  • 2020-11-30 06:39
    boolean checkElements(int arr[],  int first, int last) {
        while(arr.length > first) {
            if(arr[i] > arr[last-1]) {
                if(arr[i] > arr[i+1])
                    return checkElements(arr, first+1, first+2);;
                return false;
            }else {
                if(arr[i] < arr[i+1])
                    return checkElements(arr, first+1, first+2);
                return false;
            }
        }
        return true;
    }
    
    0 讨论(0)
提交回复
热议问题