Fastest way to check if an array is sorted

后端 未结 9 2056
走了就别回头了
走了就别回头了 2020-12-05 19:36

Considering there is an array returned from a function which is of very large size.

What will be the fastest approach to test if the array is sorted?

9条回答
  •  借酒劲吻你
    2020-12-05 20:27

    Here is my version of the function IsSorted

    public static bool IsSorted(int[] arr)
    {               
        int last = arr.Length - 1;
        if (last < 1) return true;
    
        int i = 0;
    
        while(i < last && arr[i] <= arr[i + 1])
            i++;
    
        return i == last;
    }
    

    While this function is a bit faster than in the question, it will do fewer assignments and comparisons than anything has been posted so far. In the worst case, it does 2n+1 comparisons. It still can be improved if you can make a reasonable assumption about the nature of the data like minimum data size or array contains even number of elements.

提交回复
热议问题