Check if an array is sorted, return true or false

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

    A descending array is also sorted. To account for both ascending and descending arrays, I use the following:

    public static boolean isSorted(int[] a){
        boolean isSorted = true;
        boolean isAscending = a[1] > a[0];
        if(isAscending) {
            for (int i = 0; i < a.length-1; i++) {
                if(a[i] > a[i+1]) {
                    isSorted = false;
                    break;
                }           
            }
        } else {//descending
            for (int i = 0; i < a.length-1; i++) {
                if(a[i] < a[i+1]) {
                    isSorted = false;
                    break;
                }           
            }  
        }    
        return isSorted;
    }
    

提交回复
热议问题