How to check if array is already sorted

后端 未结 7 1560
孤独总比滥情好
孤独总比滥情好 2020-12-03 21:39

so how to make such logic

int[] arr = {2, 5, 3};

if (/* arr is sorted */)
    ....
else 
    ...

Its bad that method Array.sort is void

7条回答
  •  被撕碎了的回忆
    2020-12-03 22:23

    public static boolean isSorted(int[] arr) {
        for (int i = 0; i < arr.length - 1; i++) {
            if (a[i + 1] < a[i]) {
                return false;
            };
        }
        return true;
    }
    

提交回复
热议问题