Check if an array is sorted, return true or false

前端 未结 13 1916
隐瞒了意图╮
隐瞒了意图╮ 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:56

    To check whether array is sorted or not we can compare adjacent elements in array.

    Check for boundary conditions of null & a.length == 0

    public static boolean isSorted(int[] a){    
    
        if(a == null) {
            //Depends on what you have to return for null condition
            return false;
        }
        else if(a.length == 0) {
            return true;
        }
        //If we find any element which is greater then its next element we return false.
        for (int i = 0; i < a.length-1; i++) {
            if(a[i] > a[i+1]) {
                return false;
            }           
        }
        //If array is finished processing then return true as all elements passed the test.
        return true;
    }
    
    0 讨论(0)
提交回复
热议问题