Fastest way to check if an array is sorted

后端 未结 9 2064
走了就别回头了
走了就别回头了 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:21

    The only improvement i can think of is check both ends of the array at the same time, this little change will do it in half time...

    public static bool IsSorted(int[] arr)
    {
    int l = arr.Length;
    for (int i = 1; i < l/2 + 1 ; i++)
    {
        if (arr[i - 1] > arr[i] || arr[l-i] < arr[l-i-1])
        {
        return false;
        }
    }
    return true;
    }
    

提交回复
热议问题