Home > Blockchain >  In Java, how fast is sorting of an already sorted List?
In Java, how fast is sorting of an already sorted List?

Time:06-05

So I have a List, and I need to sort it. Now, because my code is currently looking a bit like mom's spaghetti, I'm wondering if I call the .sort method on that List when it's already sorted, is that sort going to first check whether the list is already sorted and just call it a day, thus taking very little time, or is it just going to run the entire sorting algorithm and take just as much time as it would if the List wasn't sorted?

CodePudding user response:

Sorting an already sorted list in java using the built-in sort method is linear.

Java uses Timsort, see https://en.wikipedia.org/wiki/Timsort#Analysis :

In the best case, which occurs when the input is already sorted, it runs in linear time

  • Related