Fastest way to check if an array is sorted

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

    The question that comes to my mind is "why"?

    Is it to avoid re-sorting an already-sorted list? If yes, just use Timsort (standard in Python and Java). It's quite good at taking advantage of an array/list being already sorted, or almost sorted. Despite how good Timsort is at this, it's better to not sort inside a loop.

    Another alternative is to use a datastructure that is innately sorted, like a treap, red-black tree or AVL tree. These are good alternatives to sorting inside a loop.

提交回复
热议问题