How to check if array is already sorted

后端 未结 7 1559
孤独总比滥情好
孤独总比滥情好 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:19

    Well you can check it in O(n) worst case linear time. A non-sorted array (assuming you mean sorting in ascending order) will have a trip point. That is at some point arr[i] > arr[i+1]

    All you need to do is

    boolean is_array_sorted(int arr[]) {
      for(int i=0; i < arr.len-1; i++) {
        if(arr[i] > arr[i+1]) {
           return false;
        }
      }
      return true;
    }
    

    Just change the > to < if your array sort is supposed to be descending order

提交回复
热议问题