Check if an array is sorted, return true or false

前端 未结 13 1983
隐瞒了意图╮
隐瞒了意图╮ 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;
    
        }
    
    }
    

提交回复
热议问题