How to check if array is already sorted

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

    You don't need to sort your array to check if it's sorted. Loop over each consecutive pair of elements and check if the first is less than the second; if you find a pair for which this isn't true, the array is not sorted.

    boolean sorted = true;
    
    for (int i = 0; i < arr.length - 1; i++) {
        if (arr[i] > arr[i+1]) {
            sorted = false;
            break;
        }
    }
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 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;
    }
    
    0 讨论(0)
  • 2020-12-03 22:29
    function isArraySorted(arr){
        for(let i=0;i<arr.length;i++){
            if(arr[i+1] && (arr[i+1] > arr[i])){
                continue;
            } else if(arr[i+1] && (arr[i+1] < arr[i])){
                return false;
            }
        }
        return true;
    }
    
    this worked for me.
    
    0 讨论(0)
  • 2020-12-03 22:31
    public static <T>
    boolean isArraySorted(T[] elements, Comparator<? super T> cmp) {
      int n = elements.length;
      for (int i = 1; i < n; ++i) {
        if (cmp.compare(elements[i-1], elements[i]) > 0) { return false; }
      }
      return true;
    }
    
    0 讨论(0)
  • 2020-12-03 22:31

    A shorter version:

    [0,1,2,3,4].reduce((a,v) => (a!==false) && (a <= v) ? v : false, -Infinity)
    [4,3,1,2,0].reduce((a,v) => (a!==false) && (a >= v) ? v : false, +Infinity)
    

    Be careful, as in some cases it isn't effective because it will loop through entire array without breaking prematurely.

    Array.prototype.reduce()

    0 讨论(0)
提交回复
热议问题